# Question
Title: Unity, rb.MovePosition and transform.Rotate at the same time
I can't figure out why my object can't move and turn at the same time.

```
    public float moveSpeed;
private Vector3 rotationSpeed;
public Camera cam;

public Vector3 straightForward;

public Quaternion spreadAngleRight;
public Quaternion spreadAngleLeft;

public Vector3 localRightVector;
public Vector3 localLeftVector;

public Vector3 newVectorRight;
public Vector3 newVectorLeft;

private Rigidbody rb;

Vector3 movement;
void Start () {
    rb = gameObject.GetComponent<Rigidbody> ();
    rotationSpeed = new Vector3(0, 100, 0);

    straightForward = transform.TransformDirection (Vector3.forward);

    spreadAngleRight = Quaternion.AngleAxis (45, new Vector3 (0, 1, 0));
    spreadAngleLeft = Quaternion.AngleAxis (315, new Vector3 (0, 1, 0));

    localRightVector = spreadAngleRight * straightForward;
    localLeftVector = spreadAngleLeft * straightForward;

    newVectorRight = transform.TransformDirection (localRightVector);
    newVectorLeft = transform.TransformDirection (localLeftVector);
}

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

    #region Control
    if(Input.GetKey(KeyCode.W)){
        rb.MovePosition(transform.position + transform.TransformDirection(Vector3.forward * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey (KeyCode.A)) {
        rb.MovePosition(transform.position + transform.TransformDirection(-Vector3.right * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey (KeyCode.S)) {
        rb.MovePosition(transform.position + transform.TransformDirection(-Vector3.forward * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey (KeyCode.D)) {
        rb.MovePosition(transform.position + transform.TransformDirection(Vector3.right * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.D)){
        rb.MovePosition(transform.position + transform.TransformDirection(newVectorRight * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.W) && Input.GetKey(KeyCode.A)){
        rb.MovePosition(transform.position + transform.TransformDirection(newVectorLeft * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.D)){
        rb.MovePosition(transform.position - transform.TransformDirection(newVectorLeft * moveSpeed) * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.S) && Input.GetKey(KeyCode.A)){
        rb.MovePosition(transform.position - transform.TransformDirection(newVectorRight * moveSpeed) * Time.deltaTime);
    }
    Vector3 mouseInputX = Input.GetAxis ("Mouse X") * rotationSpeed;
    Vector3 mouseInputY = Input.GetAxis ("Mouse Y") * rotationSpeed;

    gameObject.transform.Rotate (mouseInputX * Time.deltaTime, Space.Self);
    cam.transform.LookAt(gameObject.transform.position + Vector3.up * 2f);

    #endregion
}

```

# Answer
> 2 votes
**Transform.Rotate** is used for transforms (I know, excuse the redundancy). If you are already displacing with **Rigidbody**, then use **Rigidbody.MoveRotation** (it takes a quaternion as parameter). Example:

```
public Vector3 rotationVelocity;

void Update()
{
    Quaternion deltaRotation = Quaternion.Euler(rotationVelocity * Time.deltaTime);
    rb.MoveRotation(rb.rotation * deltaRotation)
}

```

# Answer
> 0 votes
If you're using rigidbody for movement you should also use rigidbody for rotation. Note that transform.Rotate acts on the **Transform** component, which is present in every Unity's GameObject.

To rotate a **Rigidbody**, i.e. a GameObject with a Rigidbody component attached, you should probably use rb.MoveRotation, which will use the *interpolation setting* of your component.

However, if you do want to rotate using Transform and want your character to move always forwards, in the direction it is looking at, there's a simpler solution that should work just fine:

```
if(Input.GetKey(KeyCode.D)){
    //Rotate to the right (D), for example
    transform.rotation = Quaternion.LookRotation(transform.right);
    //Move always to the forward vector
    rb.MovePosition(transform.position + transform.forward * speed);
}

```

Now just use *transform.right - 1* to rotate to left (A), *transform.forward* (W) to rotate to forward and *transform.forward - 1* to rotate to back (S).

This will ensure you can rotate to any position and keep moving forward relative to this rotation.

You may asking how you would rotate between W and D for example, and this is simple, just sum up the vectors:

```
//If pressing W and D:
transform.rotation = Quaternion.LookRotation(transform.right + transform.forward)

```

And so on with W + A *(transform.forward + (-transform.right))*, S + D *(transform.forward + transform.right)*, S + A *(-transform.forward + (-transform.right))*.

(I don't tested this code but it should work just fine)

---

I may have misunderstood what you're trying to achieve. You're trying to make your player rotate with mouse and move always forward relative to that rotation? In this case, try:

```
//Get rotation from mouse and set to object's rotation:
transform.Rotate (mouseInputX * Time.deltaTime, Space.Self);
//if pressing forward
if(Input.GetKey(KeyCode.W)){
    rb.MovePosition(transform.position + (transform.forward * speed));
}
//if pressing right, for example
else if (Input.GetKey(KeyCode.D)){
    rb.MovePosition(transform.position + (transform.right * speed));
}

```

And do this for all key presses and sum the vectors as I explained before for when you press two buttons at the same time:

```
//If pressing W and D:
rb.MovePosition(transform.position (transform.right + transform.forward * speed));

```

This should do the trick, although I'm not sure you're using the best method to rotate acording to mouse position. Maybe take the mouse position and use **LookAt**, for example.

# Answer
> 0 votes
Not sure if you found the answer, but I had the same problem and found out that the rotating item must be Dynamic for this to work, and of course with Gravity and mass all set to nothing. You also need to manually move its position each update to pin it back onto the player.

In my scenario, I had a a Dynamic player (Parent) using Velocity to move, which had a Childed object (Aimer) programmed to track the position of the mouse cursor. In LateUpdate, right before the physics engine did its calcs, it was told to moveposition to stick onto the Player. Now here's the problem.

If it was set to Dynamic it would rotate fine but either stay fixed in its original XY position on the screen(basicaly, it didnt follow anybodys Physics but its own) or even be affected by gravity and fall out of the map!

If the object was set to Static it would just lock its position and stay on the map at its starting location with an error message saying it couldn't be given these type of orders.

If it was set to Kinematic it would stick to the Parent with no problems, but NOT continue to be Childed while physics calculations were going on, so it would "freeze" during player movement and "teleport" into its correct position after movement had halted. Enabling the Aimer to be dynamic meant it could be pushed around with the same physics (velocity / addforce).

In the end I had to use Dynamic aimer with Physics enabled in order to get the free rotation in realtime *while the Parent was also experiencing physics*, and then I added script to manually pin the Aimer to the same coordinates as the player, every LateUpdate.

---
Tags: unity, rotation, movement, gameobject, rigidbody
---


# Question
Title: Character Action Sprite Framelength of Late-90's Something, Industry Standards of that Era?
I'm making a 3d character that emulates a sprite. The game as a whole emulates the feel of a classic RPG game.

Old games like Ultima Online, or Diablo...or similar late-90's generation...

For an average run sequence, they must have had general targets for "smoothness". I'm curious if there was an old industry standard of that time for "sprite frames for this action" in game design.

Example. A walk sequence in Diablo. How many frames would they have targeted in those years?

I'm looking for a general guideline to emulate "that cool 90's RPG". I'd love some advice.

If there was no such standard, and designers of old were as hacky as they tended to be, I'll also take a good educated opinion on the matter.

# Answer
Original Diablo uses 8 frames for its walk cycles.

Here we have the Black Night walking cycle:

*Black Knight walking animation.*

We can see it takes 4 frames on each step (4 frames for the left, 4 frames for the right).

The 4 frame for each step are:

1. Contact: Both feet in contact with the ground, far apart.
2. Down/Recoil: Legs bent. *In the animation above we don't see the lower part of the far leg, only down to the knee.*
3. Pass: The previously far leg is passing to the front. It is clearly not making contact with the ground.
4. Up/High point: The leg that has now moved up and to the front in anticipation of making contact with the ground again.

*Repeat for both leg.*

---

Other animations can take up to 24 frames. Here a 16 frame action:

*Black Knight Attack animation.*

This animation is (by my count) 5 frame windup, 4 frames attack, and 7 frames recovery.

---

Finally this is a 24 frames animation:

*Black Knight death animation.*

---

*The animations above were taken from taken diablo.fandom.com, where they were uploaded by the user Deathcharger.*

*You can also find sprite sheets on spriters-resource.com (which I'm only suggesting for learning purposes). There the user sutinoer has uploaded Black Knight sprites from Diablo.*
> 0 votes

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


# Question
Title: Issue picking the closest vector in a unique circumstance
I have a list of targets that can be picked depending on the magnitude from the vector created using:

```
  for(int i = 0; i < targetQueue.Count; i++) //2 loops to cycle through targets
            {
                for(int j = 0; j < targetQueue.Count; j++)
                {   //if two targets are the same, then skip them
                    if(targetQueue[i] != targetQueue [j])
                    {
                        //getting the direction using the source and destination vectors
                        Vector3 iDir = targetQueue[i].transform.position - transform.position;
                        Vector3 jDir = targetQueue[j].transform.position - transform.position;

                        //comparing i with j, if i is less than target at j then match found
                        if(iDir.magnitude < jDir.magnitude)
                        { //LockedTarget is a gameobject to show what target the turret is locked on to
                            LockedTarget = targetQueue[i]; //if match found then set locked target to target at i
                            break;
                        }
                    }
                 }
             }

```

This code compares every target to each other, however it does this twice, once on each side( `target[i]` becomes `target[j]`). When the magnitude is compared, if the `target[i]` is smaller, then this is now the locked target as this target is closer to the turret.

This works every time except for one instance and I can't figure out why its happening here:

When both targets are inside the collider, the target on the right should still be highlighted, yet I get the target that is farther away being selected, this also occurs with more than two targets, with even stranger results. These being that the original target chosen for 'DEADLOCK' what i'm calling it, stays locked. Even when I move the other targets above, below, left and to the right of it.

This only occurs with this target, i've tried with 2 other targets (south of the turret) and it works as intended by properly switching based on size of magnitude of the direction vector between the target and the source.

I have ruled out the possibility being that it is an issue to do with adding target's to the gameobject list as it works everywhere else. When measuring the lengths of the magnitudes, the wrong target is chosen as the locked target. It does show that the closest target on the images does actually have the smallest vector magnitude.

UPDATE: the magnitudes of the vectors are increasing and decreasing by tiny amounts, 1 to 2 for a major movement. this makes sense as its worldPos. What doesn't make sense is the target on the right having a magnitude of 49 and the target above having a magnitude of 82, when according to world space they are pretty close to eachother.

Can anyone help me with this issue? its been driving me nuts for days.

It must be to do with the magnitudes of the direction vectors not being calculated properly.

# Answer
> 1 votes
This looks like a choice of the wrong algorithm for the job.

The code you've written does not find the closest transform in the collection. It does something more complicated. It returns the *last* transform in the list that's closer than *at least one* other transform in the list.

So if you have three objects `{close, medium, far}`, then this will return `medium`, because it comes after than `close` in the list, but still wins in its comparison against `far`.

If you just want the closest target, you can do this much more simply with a single loop:

```
float closestDistance = float.PositiveInfinity;
Transform closestTarget = null;

foreach (var target in targetQueue) {
    // Using sqrMagnitude lets us skip unnecessary square roots.
    float distance = (target.position - transform.position).sqrMagnitude;
    if (distance > closestDistance)
        continue;

    closestDistance = distance;
    closestTarget = target;
}

if (closestTarget != null) {
    // ...Do something with your selected target.
}

```

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


# Question
Title: Is non-indexed, non-instanced rendering useful anymore?
I'm adding batched rendering to my game engine and I'm wondering: Should I support non-indexed, non-instanced batches or just indexed and/or instanced?

It's my understanding that the concept of indexed rendering was invented after pure "vertex only" drawing. That said, is supporting vertex-only rendering useful anymore? Is there a modern use-case for it?

# Answer
If you're looking to simplify down, then it may be helpful to bear the following in mind:

* 1 is a valid value for number of instances.
* An index buffer of 0,1,2,3,4,5,6,etc can replicate non-indexed rendering.

In that sense, you can certainly have all of your draw calls be indexed instanced calls, yet still be able to deal with unforseen cases where either or both of non-instanced or non-indexed may seem to be needed.

It can also be instructive to look at how modern APIs handle this, so:

* In Vulkan, every draw call is an instanced draw call (*bearing in mind that 1 is still a valid value for number of instances*), but separate draw calls still exist for indexed and non-indexed cases.
* Direct3D 12 likewise only has DrawInstanced and DrawIndexedInstanced.

So this suggests that even for modern use, there is still benefit to be gained from supporting non-indexed cases, but not from non-instanced cases.

So what non-indexed cases still exist? Looking over some of my own code, I use non-indexed for the following:

* Lists of points in a particle system.
* Full-screen post-processing passes.
* Some 2D UI elements.
> 2 votes

---
Tags: directx11
---


title: Tiled Map Editor Vs Text File? | Pygame

text:
# Question
Title: Tiled Map Editor Vs Text File? | Pygame
I've only recently got into coding and was looking around on how to create a 2D platformer, a lot of tutorials I've seen have used text files to create their maps. However, one I saw in particular spoke of Tiled Map Editor which allows you to create your mape then parse it to pygame.

My question is which is better in the long run? Should I create text file maps with character representing each sprite/player/mob or should I use Tiled to create all my maps then use it's obstacle layer feature to outline where players spawn, wall, boundaries etc?

# Answer
My suggestion would be to do both:

* Start by just following the tutorials and using the text file. This will give you a nice way of getting your head around what's going on in the code, and how you can easily play with the data
* Once you're comfortable with this, move on to using Tiled (or similar). This is a more advanced tool, which needs to be coded around a little differently. As I remember, it contains multiple layers which you can use to hold all sorts of data, and the format is XML rather than text, so you can hold more information about your map, in a structured format. (e.g. this tile looks like X, and allows player to cross TRUE, and can be shot through TRUE)
> 2 votes

---
Tags: maps, pygame, tiled
---


title: Why is my texture spilling?

text:
# Question
Title: Why is my texture spilling?
I'm trying to create a 3D Sword Slash VFX and created the model for the effect in blender. It's basically a wedge or ufo-shaped mesh. I proceeded to paint a simple test texture to see how it would look in Unreal. Now, the UVs are setup correctly for the effect itself (bottom of the texture is outside of the ring and top of the texture is inside of the ring), but it seems like my texture is spilling.

I got clearly visible artifacts and I don't really know why. The artificats go away when I start erasing parts of texture at the bottom, but it also leads to the outside edge of the wedge model to get a gap. What can I do to prevent my texture from spilling over?

---

**\*Edit:** Making the material I used Unlit helped, but it did not get rid off the problem completely. Using clamp is not an option for me, because I want to animate the texture with a UV-Offset to make it rotate. In the material editor preview there are no artifacts, but in the material instance preview window they appear again.

I created the mesh in this way: add a circle, extrude the edges up and then scale the vertices down. Then do the same but at the bottom. In the UV-Editor I dragged the UVs from the outside edge to the bottom and the vertices from the top circle and bottom circle to the top of the UV map.

# Answer
> 0 votes
Turns out it was my own dumbness. There were very small amounts of "dirt" in my texture for some reason. They didn't show up in my preview screen, because they were really small and had transparency on them. Cleaning everything up solved the issue. Duh!

# Answer
> 1 votes
Double-click your texture and change the X & Y Tiling Methods to Clamp instead of the default Wrap.

Image from the Unreal docs on Texture Properties

---
Tags: textures, unreal-4, blender
---


# Question
Title: Javascript snake game, configurable section distance
I want to make a snake game. In a classic game the snake moves in 4 directions, I want the player to move in all directions by mouse input, similar to slither.io

Right now the tail section changes its position after the head. If I increase the speed, the sections move away from each other. How can I make the sections not move away from each other and have a configurable distance between them?

Code snippet:

```
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// Change speed of movement
var speed = 5.0

var mouseMovementX = 0;
var mouseMovementY = 0;

document.addEventListener("mousemove", function(event){
 mouseMovementX = event.clientX;
 mouseMovementY = event.clientY;
});

var key = {
 a: false,
 s: false
}

function keyboard(){
 //$(window).keydown(function(event){
 document.addEventListener('keydown', (event) => {
  if( event.which == 83 ){
   key.s = true
  }
  if( event.which == 65 ){
   key.a = true
  }
 });
document.addEventListener('keyup', (event) => {
 //$(window).keyup(function(event){
  if( event.which == 83 ){
   key.s = false
  }
  if( event.which == 65 ){
   key.a = false
  }
 });
}

function drawCircle(x, y, rotation){
 ctx.moveTo(x, y);
 ctx.beginPath();
 ctx.arc(x,y,12,0,Math.PI*2,false);
 ctx.closePath();
 ctx.fill();
 ctx.strokeStyle = "#ccc";
 ctx.stroke();
}

function radToDeg(value){
 return ( value * 180 ) / Math.PI;
}

function degToRad(value){
 return ( value * Math.PI ) / 180;
}

// Clamp
function clamp(Ax,Ay,Bx,By,L){
 var Vx = Bx - Ax;
 var Vy = By - Ay;

 var lmax = L;
 var l = Math.sqrt( Math.pow(Vx,2) + Math.pow(Vy,2) );

 var lclamp = Math.min( l, lmax );

 var vclampX = ( Vx / l ) * lclamp
 var vclampY = ( Vy / l ) * lclamp

 var bclampX = Ax + vclampX
 var bclampY = Ay + vclampY

 return { x: bclampX, y: bclampY  }
}

// Update tail
function updateTail(i){
 for( i2 = app.object[i].body.length-1; i2 >= 0; i2--){
  if( i2 == 0 ){
   var r = clamp(
    app.object[i].head.x,
    app.object[i].head.y,
    app.object[i].body[i2].x,
    app.object[i].body[i2].y,
    app.object[i].sectionDistance
   );

   app.object[i].body[i2].x = r.x
   app.object[i].body[i2].y = r.y
  }else{
   var r = clamp(
    app.object[i].body[i2-1].x,
    app.object[i].body[i2-1].y,
    app.object[i].body[i2].x,
    app.object[i].body[i2].y,
    app.object[i].sectionDistance
   );

   app.object[i].body[i2].x = r.x
   app.object[i].body[i2].y = r.y
  }
 }
}

// Update previous positions
function updatePrevPosition(i){
 app.object[i].head.xPrev = app.object[i].head.x
 app.object[i].head.yPrev = app.object[i].head.y
 app.object[i].head.anglePrev = app.object[i].head.angle
}

var app = {
 object: []
}

// Create snake object
var options = {
 size:0,
 length:20,
 width: 24,
 height: 24,
 sectionDistance: 10,
 head: {
  x: 200,
  y: 200,
  xPrev:0,
  yPrev:0,
  angle: 0
 },
 body: []
}

app.object.push(options)

for( i = 0; i <  app.object[0].length;i++){
 app.object[0].body.push({
  x: (6*i)+200,
  y: (6*i)+200,
  angle: 0,
  color:0
 })
}

// Draw
var numberOfObjects = app.object.length;

function draw(){
 for( i = 0; i < numberOfObjects; i++ ){
  if( i == 0 ){
   for( i2 = app.object[i].body.length-1; i2 >= 0; i2-- ){
    drawCircle((canvas.width/2)+( app.object[i].body[i2].x - app.object[i].head.x) ,(canvas.height/2)+( app.object[i].body[i2].y - app.object[i].head.y ),app.object[i].body[i2].angle)
   }

   drawCircle((canvas.width/2),(canvas.height/2),app.object[i].head.angle)
  }else{
   var tempX = ( app.object[i].head.x - app.object[0].head.x ) + ( canvas.width / 2 )
   var tempY = ( app.object[i].head.y - app.object[0].head.y ) + ( canvas.height / 2 )

   drawCircle(tempX,tempY,app.object[i].head.angle)
  }
 }
}

// Update positions
function update(){

 if( key.a == true ){
  speed -= 0.1;
  if(speed < 0.1 ){ speed = 0.1 }
  console.log(speed)
 }
 if( key.s == true ){
  speed += 0.1;
  if( speed > 10 ){ speed = 10 }
  console.log(speed)
 }

 angle = ( Math.atan2(mouseMovementX - ( canvas.width / 2 ) , mouseMovementY - ( canvas.height / 2 )) * -1 );

 newX = Math.sin(angle) * speed
 newY = Math.cos(angle) * speed

 app.object[0].head.angle = angle

 app.object[0].head.x -= newX
 app.object[0].head.y += newY

 updateTail(0)
 updatePrevPosition(0)

 draw();
}

keyboard();
// Animate
function animate(){
 ctx.clearRect(0,0,canvas.width,canvas.height);
 requestAnimationFrame(animate);
 update();
}
animate();
```

```
html, body{
 width:100%;
 height:100%;
 padding:0;
 margin:0;
 background-color:blue;
}
canvas{
 display:block;
 background-color:white;
}
```

```
<canvas id="canvas" width="500" height="300"></canvas>
```

# Answer
1)Take a vector from segment A to segment B

2)Calculate vector length

3)Check if length exceeds maximum, clamp if it does

4)Normalize vector and multiply it by clamped length

5)Set position of segment B to position of A + clamped vector

Desmos graph: https://www.desmos.com/calculator/eilpcyx5gp

**EDIT:** Since segments depend on each other's position during clamping, you should go from head to tail, not from tail to head. Rewrite your loop accordingly:

`for( i2 = 0; i2 < app.object[i].body.length; i2++){`
> 0 votes

---
Tags: javascript, movement, snake
---


# Question
Title: How can I create a six sided tillable perlin noise image?
I'm attempting to create a tillable hex shaped terrain map using c++.

As part of the process I'd like to use perlin noise, but it seems that in order to make it tillable I'll need to generate it 5 dimentionally and take a "circle" from it (if you know another way please let me know, I'm basing my theory on this post: https://ronvalstar.nl/creating-tileable-noise-maps by Ron Valstar) creating three cylinders that together make up the image

I've coded my own 2d perlin noise function but getting to 5d seems like a whole different beast

Unless anyone knows of one that already exists, I think I'll have to write my own library for generating the noise. I'm working on c++, and while I've seen a few perlin noise libraries I haven't seen any with 5d. I can generate a 5d vector feild no problem but it's the actual linear algebra where I'm confused. It'd involve me doing some quin-linear interpolation and I have no clue how to even start on that. If anyone knows how to do this already or has any resources that could help I'd appreciate it.

in summary: 1) anyone know how to generate 5d perlin? 2) anyone know of a different method to tile a six sided image generated from perlin noise?

# Answer
I don't recommend using the "increase the dimensions and orbit in a cylinder" trick here. It has several disadvantages:

* More expensive to compute: Perlin noise needs to select and interpolate \\$2^d\\$ gradient vectors per evaluation, so going from 2 dimensions to 5 means doing 8x more work.
* More distortion: by evaluating it on a membrane in higher-dimensional space, there will be places where your membrane aligns with the grid lines of that space, and places where it cuts between them diagonally. This can make your noise statistically non-uniform (some areas have more contrast than others) and less band-limited (each "octave" of noise leaks into adjacent octaves' frequencies, making it harder to precisely control the look).
* More complicated code to wrap your head around, write, and maintain.

Instead, my favoured way to tile noise, whenever feasible, is to exploit the grid structure of the noise itself. Perlin-like noise works by...

1. Dividing the domain into a grid of cells (usually square cells, but stay tuned)
2. Working out which cell the sampled point lies in, and which grid points make the corners of that cell
3. Pseudo-randomly selecting a gradient vector for each corner point, so that the same gradient is always chosen for that corner
4. Computing an intensity for the sampled point according to its offset from each corner, dotted with that corner's gradient vector
5. Interpolating these intensities in a way that's continuous across cell borders (the weight for a far corner hits zero just as we cross the line into a neighbouring cell)

So, if we control these gradient vectors, we control the noise! I show an example of this strategy for a rectangular tile in this answer, the main points being:

1. Align the noise grid with the edges of the tiling region, so a grid intersection on one edge maps exactly to a grid intersection on its matching edge.
2. Modify your pseudorandom gradient vector selection so that these paired points always select the same gradient.

In your case for a hexagon, a square grid is not a great fit. But an equilateral triangle grid works too, and tiles perfectly in a hexagon.

One Perlin-like noise on a triangular grid is Simplex Noise, which has some advantages over the original square grid:

* More isotropic (less difference between grid-aligned and mis-aligned samples)
* More efficient (needs only \\$d + 1\\$ gradients per sample, instead of \\$2^d\\$)

So, making a custom Simplex Noise function whose grid aligns with your tiles, and uses your world wrap-around function to ensure matching corner pairs always get the same gradient, should be an efficient route to high-quality tiling noise for your use case.

---

Here's a working example. For starters, I built a mesh with "pointy-top" hexagons, using axial coordinates where the x-axis points up-right and the y-axis points up-left (and the third implicit axis z = -x - y points down).

The white twisted hexagon is the isometric triangle lattice we'll use to evaluate our noise, at the coarsest tiling frequency.

To make finding the 3 closest lattice points easy, we'll apply a coordinate transformation. An isometric grid is really just a square grid, split along its diagonals, and squashed slightly to make the diagonal the same length as the other sides.

(Diagram from Understanding skew factors in Simplex/Improved Perlin Noise by Kristian Nielsen)

With this trick, all our lattice points sit on integer coordinates. And we can get any finer subdivision of this grid by just multiplying our coordinates by an integer.

So to proceed, we need to transform our xy axial coordinates into these uv-space coordinates. (Here shown with a colour gradient: more red = more U, more green = more V)

To do this, lets get the positions of the ends of those U & V vectors in axial coordinates. For the coordinate system I used, that's :

```
uBasis = new Vector2(radius + 2f / 3f, -radius - 1f / 3f);
vBasis = new Vector2(        -1f / 3f,  radius + 2f / 3f);

```

We can think of these as the columns of a transformation matrix that maps (1, 0) to `uBasis` and (0, 1) to `vBasis`. To reverse that transformation, we just invert the matrix:

```
float determinant = uBasis.x * vBasis.y - uBasis.y * vBasis.x;
toU = new Vector2( vBasis.y, -vBasis.x) / determinant;
toV = new Vector2(-uBasis.y,  uBasis.x) / determinant;

```

Then we can convert the axial position of any point into UV space by writing:

```
u = Vector2.Dot(axialPosition, toU);
v = Vector2.Dot(axialPosition, toV);

```

I did this for each vertex in my hexagon mesh, and saved the results into a UV texture coordinate channel, so I could do the rest of the work in a shader. The logic is basically the same if you do this CPU-side though.

The next step is to define our noise function for a given frequency of noise. Its job will be to...

* Multiply our uv input point by the frequency, to get the fineness of grid we want.
* Floor the position to get the bottom-left corner of the diamond it's in, and add (1, 1) to get the top-right corner.
* Subtract the multiplied position from the corner to get our fractional position inside this diamond.
* Check whether we're above or below the diagonal, so we know what third corner completes our local triangle.
* Sample the gradient from each of the three corners, and add up their contributions to make the final noise output.

In my (non-optimal) shader code, that looks like this:

```
float noise(float2 uv, int frequency) {
    uv *= frequency;

    float2 cornerA = floor(uv);
    float2 cornerB = cornerA + float2(1, 1);

    // We're either in the top-left triangle or the bottom-right...
    float2 inTri = uv - cornerA;
    float2 cornerC = cornerA
                   + (inTri.y > inTri.x) ? float2(0, 1) : float2(1, 0);

    // We'll need this later to get the undistorted distance to the corner.
    float2 unskewed = unskew(uv);

    return ( corner_contribution(unskewed, cornerA, frequency)
           + corner_contribution(unskewed, cornerB, frequency)
           + corner_contribution(unskewed, cornerC, frequency)) * 40.0f;
    // The *40 just increases the contrast of the noise.
}

```

You can see I'm using a little utility function to undo the skewing we applied before and get back to regular space with perpendicular axes:

```
float2 unskew(float2 p) {
    return p - dot(p, 1.0f) * (1.0f - 1.0f / sqrt(2.0f + 1.0f)) / 2.0f;
}

```

Next we need to define our corner contribution function. It will need to:

* Compute the unskewed displacement between this corner and our sample point, to use in calculating the value to add.
* Wrap the corner around to make sure the borders of our outermost hexagon match up.
* Use the wrapped corner positions to pseudo-randomly select a gradient vector.
* Dot the gradient with our displacement vector to get the brightness due to this corner.
* Weight this value so that it fades out radially as we get further from the corner.

That can look like this:

```
float corner_contribution(float2 unskewed, float2 corner, int frequency) {
    float2 delta = unskewed - unskew(corner);

    corner = wrap_corner(corner, frequency);

    // You can use any method you like to hash-together these inputs to make
    // a pseudo-random value. I like to include frequency to decorrelate octaves.
    float randomHash = pseudo_random(corner.y, corner.x, seed + frequency));

    // Similarly, you can use any method you like to look up / make a gradient
    // unit vector given this random input. (cos(randomAngle), sin(randomAngle)) works.
    float2 gradient = get_unit_gradient(randomHash);

    float weight = max(0.5f - dot(delta, delta), 0.0f);
    weight *= weight;
    weight *= weight;

    return weight * dot(delta, gradient);
}

```

Okay, finally we get to where the magic happens: the wrapping of our corners to ensure that opposite sides of our hexagon are choosing the same pseudo-random gradient, for seamless tiling.

Inside this method, we're going to be working with integer points on a stretched hexagon that looks like this:

Note that at the six outer corners, we're really only allowed to use two distinct values. As soon as we pick a value for one corner, we have to pick the same value for two other corners, in order to match our adjacent repeats.

Apart from these special corners, our goal will be to determine whether we're on the remappped edge of, or inside of, one of the six neighbouring hexes. If we are, we want to shift that hex back to the origin, to bring our sampling point to a canonical point inside/on a non-remapped edge of our central hex.

There are probably much more elegant ways to do this wrapping, but here's my stubborn kluge:

```
float2 wrap_corner(float2 corner, int frequency) {
    // Reintroduce a third axis z, pointing perpendicular to our diagonal side.
    float3 hex = float3(corner.xy, corner.y - corner.x);
    // We'll exploit some symmetry using absolute value & sign information.
    float3 hexSign = sign(hex);
    float3 absolute = hexSign * hex;

    // Remap the outer corners at (±frequency, 0) and (0, ±frequency)
    // to the corners at the ends of the diagonal.
    if (max(absolute.x, absolute.y) == frequency
    && (absolute.x + absolute.y == frequency))
        return (hexSign.x + hexSign.y) * float2(-frequency, -frequency);

    // We want to remap corners from one side to the other side,
    // not exchange both sides! So shifting our threshold excludes one side.
    absolute -= hexSign * 0.1f;

    // Points safely away from our remapped border, or the two diagonal corners,
    // can stay exactly where they are.
    if (max(absolute.x, max(absolute.y, absolute.z)) < frequency
        || hex.z == 0.0f)
        return corner;

    // If we're in either of the two neighbouring hexes in quadrant I or III...
    if (corner.x * corner.y > 0) {
        // Shift depending on whether we're in the top or bottom neighbour hex.
        float shift = step(absolute.x, absolute.y);
        corner += hexSign.x * frequency * float2(-2 + shift, -1 - shift);
    } else { // Otherwise, we're in quadrant II or IV
        corner += hexSign.z * frequency * float2(1, -1);
    }

    return corner;
}

```

With this in hand, you can make hexagon-tiling noise of any integer frequency (here I show 1, 2, 3, 4, and 8):

Or you can sum multiple octaves at different frequencies and amplitudes to get a cloudy FBM/turbulence look like in the first image. Or apply any of the other standard techniques you might use with Perlin noise, like Ridge noise, etc.
> 11 votes

---
Tags: algorithm, perlin-noise, tiled, hexagonal-grid, noise
---


# Question
Title: ECS as part of the rendering pipeline of an engine
I'm trying to integrate ECS design into my game engine.

Currently I'm trying to mimic the components of unity (although not pure ECS) with `MeshFilter` (holds `Mesh` object) and `MeshRenderer` (holds various attributes such as `castShadows`, `receiveShadows` etc..) components.

I also have `MeshRenderer` system which I defined such as that it gets all entities with `MeshFilter` and `MeshRenderer` components so it could basically render these meshes.

The logic of the `MeshRenderer` system would basically be:

1. iterate the entities
2. grab the `Mesh` from the `MeshFilter`
3. grab the `Material` from the `Mesh`
4. use relevant `Texture`s and `Shader`s from the `Material` to draw the mesh

This is all fine but I wish to represent lights as entities as-well. I've made relevant components such as `DirectionalLight`, `SpotLight` etc.. that holds relevant information such as attenuation, color, shadow map (another object that holds `RenderBuffer` object of the shadow map) etc..

Now it seems to me that this `MeshRenderer` system should also take into account any entity with `XXXLight` components as-well since part of the rendering of an object is to also take into account any lights in the scene and also generate relevant shadows from/upon it.

Problem is that the system is defined to operate on entities with `MeshFilter` and `MeshRenderer` component and I'm not sure what to do. Should I make it so systems could operate on a list of entities with relevant components? Wouldn't it make the logic of the system's `Update` method a mess which entity is render-able mesh and which is light and then plug it all together?

I'm wondering what would be the best course of action here, what can I do?

# Answer
As DMGregory already pointed out, it might be beneficial to - instead of just one MeshRendering system as you proposed - setup / control the OpenGL state in some centralized RenderingPipeline, and execute specific systems at different points in this rendering pipeline.
For reference, I've had a similar problem some time ago, here's how I integrated rendering pipelines into my implementation of an ECS:
Next to the "usual" systems with an update method, there are 'RenderSystems', which are just systems with a render() method and a RenderStage field. The RenderStages are static enums like `RENDER_STAGE_DEFERRED_GEOMETRY_PASS` or `RENDER_STAGE_DIRECTIONAL_LIGHTING` etc.
For each render stage, the ECS holds a list of references to render systems that should run during that stage, and a method to run all render systems for a specific stage that can be called from some form of RenderingPipeline.
The RenderingPipeline takes care of setting up the OpenGL state for a render pass, e.g. binding the required buffers (e.g. a G-Buffer, or some form of Light- or Post-Processing-Framebuffer), and instructing the ECS to execute all systems in a specific RenderStage (e.g. the RenderingPipeline calls`ecs.render(RENDER_STAGE_DEFERRED_GEOMETRY_PASS` once the G-Buffer is setup and bound, or combines all the rendered data (geometry buffer, shadow buffers, light buffers) into a final image after all systems have finished rendering by means of a filter / post-processing stage (which RenderSystems can also hook onto).
Some pros and cons I found when utilizing this approach:

* Holding a set of references to another set of systems makes the implementation kind of clumsy and bloats the underlying core of the ECS
* Rendering was split up into many different systems, making it potentially harder to get a good overview of the implementation
* The systems allow entities to essentially render themselves when the correct OpenGL state has been set
* Everything has to be orchestrated by the RenderingPipeline (never call `ecs.render(RENDER_STAGE_POINT_SHADOW_PASS)`? No Point-Light shadows for you.)
* Adding aspects to an entity that require rendering became very easy (Want something to have a shadow? Attach a ShadowComponent to the Entity so that it is picked up by the (Directional/Point)ShadowRenderingSystem and rendered to a depth-buffer at a specific render stage)

Maybe this helps, maybe not, anyway, good luck :)
> 1 votes

---
Tags: opengl, pipeline, entity-component-system
---


# Question
Title: Why are 2D game tiles often lit from the top left?
I have been in to game programming for some time now, and recently ventured out in to trying to create my own pixel art. So I have learned the basics of lighting and shading etc. and noticed that several games will light their tiles from the top left. Such as Super Metroid and Axiom Verge highlighted in red here:

I assume because there is no distinct light source, one was chosen and consistently applied everywhere where possible?

Why does it tend to be the top left, is it to do with westerners reading left to right, top to bottom perhaps?

And bonus question, what is the reason behind the opposite side shading shown in the blue circle in Axiom Verge?

# Answer
I've been thinking about this for some time too.

It's a pure speculation, but I think it's because the same lighting is normally used for the real-life writing desks (and drawing desks). You don't want the shadow from your hand to obstruct the paper, so if you're right-handed, you want light to come from the top-left.

So, someone who writes or draws on paper a lot might subconsciously consider this to be the default lighting.
> 1 votes

---
Tags: 2d, lighting, tiles
---


title: Room Detection on a Tilemap

text:
# Question
Title: Room Detection on a Tilemap
I am working on a 2D top-down game inspired by Prison Architect. What I just can't wrap my head around is recognizing rooms built by the player.

The game is built on a tilemap, meaning the map is always a rectangle, while the rooms can be of any shape. I'd like to be able to detect whenever walls & doors create a new wall, like in the example below.

Since I have no formal education in CS (yet), I can't think of any algorithm or class of algorithms that might be of use here and also can't figure out one by myself. So if you have any ideas, suggestions or resources, I'd be very thankful!

In case this is relevant, I am using a custom implementation of a tilemap using Monogame, a reimplementation of XNA and Nez.

# Answer
> 3 votes
Here's an example of depth-first search implemented in python, finding all squares of the same type and connected to a given input square:

```
maze = """\
*********
*    * **
*    D  *
**D*** **
*    * **
*   **  *
**   D  *
*********""".split('\n')

dr = [-1, +1, 0, 0]
dc = [0, 0, -1, +1]

def all_tiles_of_same_type(maze, r, c):
    tile_type = maze[r][c]
    tiles = set()
    todo = [(r, c)]
    while len(todo) > 0:
        cell = todo.pop()
        if cell in tiles:
            continue
        tiles.add(cell)
        r, c = cell
        for i in (0, 1, 2, 3):
            r2 = r + dr[i]
            c2 = c + dc[i]
            add_nbr = (0 <= r2 and r2 < len(maze) and
                       0 <= c2 and c2 < len(maze[r2]) and
                       maze[r2][c2] == tile_type)
            if add_nbr:
                todo.append((r2, c2))
    return tiles

print sorted(all_tiles_of_same_type(maze, 1, 1))
print sorted(all_tiles_of_same_type(maze, 3, 3))

```

Here are the main ideas:

* `tiles` keeps track of the result, adding squares as they are discovered
* `todo` holds a list of squares that must be visited in the future
* When we visit a square, we add all its neighbors to the `todo` list—or rather, all the *relevant* (same-type) neighbors. That happens in `for i in (0, 1, 2, 3): ...`.
* If we have already visited a square we should not visit it again, otherwise we will go into an infinite loop. That's what `if cell in tiles: continue` does.
* What makes this a depth-first traversal is our use of a stack: `cell = todo.pop()` removes from the end of `todo`, and `todo.append(...)` adds to the end as well. If instead we had used a queue, we would've done a breadth-first traversal.

Note that we don't explicitly construct a tree—but we could: whenever we add a neighbor of `(r, c)` to the `todo` list (and that neighbor hasn't already been visited), add an edge from `(r, c)` to the neighbor. Use the `(r, c)` given as inputs as the root of the tree. That would be the DFS traversal tree.

# Answer
> 2 votes
As far as I understand your question, you want to compute the regions of your map that would be flood-filled in a paint program. In that case, I recommend one of the following approaches:

In case of the disjoint set data structure, you would union together each pair of neighboring grid cells. Once you have done that for all pairs, two squares `s1` and `s2` are in the same room if `Find(s1) == Find(s2)`.

---
Tags: algorithm, monogame, tilemap
---


# Question
Title: From 3d rotation, snap to nearest 90 directions
I have a 4x4 transformation matrix, made only from successive rotations and translations, and I'd like to "snap" my object to the "nearest" of the 24 orthogonal (multiples of 90 degree) rotations.

I'm not sure how to think of the problem. Round each element of the upper 3x3 matrix to -1, 0, and +1 (cutting at .707)? I am pretty sure that would be too good to be true. Another possibility would be to convert to axis-and-rotation or quaternion, but would that make it simpler somehow? I'm not fluent in those manipulations.

Any guidance most welcome!

# Answer
> 3 votes
Not sure if this is the most performant, but it can be visualized easily:

//assuming you're starting with a relatively orthonormal matrix

1.) Take one of your matrix's 3 basis vectors and dot it against the 6 world orthogonal vectors and set it to the one whose result is closest to 1.0.

2.) Do the same for one of the 2 remaining basis vectors.

3.) Cross the two that you just reset to determine and reset the third basis vector.

# Answer
> 4 votes
For anyone in the future looking for a solution to this using Unity/C#, here is an implementation I made based on Steve's answer:

```
//takes a rotation and returns the rotation that is the closest with all axes pointing at 90 degree intervals to the identity quaternion
Quaternion snapToNearestRightAngle(Quaternion currentRotation)
{
    Vector3 closestToForward = closestToAxis(currentRotation, Vector3.forward);
    Vector3 closestToUp = closestToAxis(currentRotation, Vector3.up);
    return Quaternion.LookRotation(closestToForward, closestToUp);
}

//finds the axis that is closest to the currentRotations local axis
Vector3 closestToAxis(Quaternion currentRotation, Vector3 axis)
{
    Vector3[] checkAxes = new Vector3[] { Vector3.forward, Vector3.right, Vector3.up, -Vector3.forward, -Vector3.right, -Vector3.up };
    Vector3 closestToAxis = Vector3.forward;
    float highestDot = -1;
    foreach (Vector3 checkAxis in checkAxes)
        check(ref highestDot, ref closestToAxis, currentRotation, axis, checkAxis);
    return closestToAxis;
}

//finds the closest axis to the input rotations specified axis
void check(ref float highestDot, ref Vector3 closest, Quaternion currentRotation, Vector3 axis, Vector3 checkDir)
{
    float dot = Vector3.Dot(currentRotation * axis, checkDir);
    if (dot > highestDot)
    {
        highestDot = dot;
        closest = checkDir;
    }
}

```

And here is an implementation based on this post which is much more efficient:

```
//takes a rotation and returns the rotation that is the closest with all axes pointing at 90 degree intervals to the identity quaternion
Quaternion snapToNearestRightAngle(Quaternion currentRotation)
{
    Vector3 closestToForward = SnappedToNearestAxis(currentRotation * Vector3.forward);
    Vector3 closestToUp = SnappedToNearestAxis(currentRotation * Vector3.up);
    return Quaternion.LookRotation(closestToForward, closestToUp);
}

//find the world axis that is closest to direction
Vector3 SnappedToNearestAxis(Vector3 direction)
{
    float x = Mathf.Abs(direction.x);
    float y = Mathf.Abs(direction.y);
    float z = Mathf.Abs(direction.z);
    if (x > y && x > z)
    {
        return new Vector3(Mathf.Sign(direction.x), 0, 0);
    }
    else if (y > x && y > z)
    {
        return new Vector3(0, Mathf.Sign(direction.y), 0);
    }
    else
    {
        return new Vector3(0, 0, Mathf.Sign(direction.z));
    }
}

```

---
Tags: rotation, matrix
---


# Question
Title: Set Rigidbody velocity in FixedUpdate() or Start()?
I'm developing a simple 2D game in Unity (balls hitting bricks), so I have a ball and I want to fire the ball to hit bricks. Now, to fire the ball I have to set `velocity` on the `Rigidbody` component attached to the ball's `GameObject`.

There are two ways to do that:

**Method 1:**

*Set the velocity inside the Start() method*

```
private void Start()
{
    rb.velocity = direction * speed;
}

```

**Method 2:**

*Write a FixedUpdate() method and put the statement in there.* because:

> Use FixedUpdate when using Rigidbody. (Unity Docs)

```
private void Start()
{
    _setVelocity = true;
}

private void FixedUpdate()
{
    if (!_setVelocity) return;

    rb.velocity = direction * speed;
    rb.angularVelocity = 0;
    rb.gravityScale = 0;
    _setVelocity = false;
}

```

**But the thing is:** I don't need the `FixedUpdate()` method for anything else, because I only fire the ball once in its script's lifespan, so after I fire the ball Unity will continue to run the `FixedUpdate()` method and check for `_setVelocity`'s value and `return` (exit) every time because it will always be `false` after I shoot the ball the first time.

And this will happen every fixed time step which is expensive I guess for just setting the velocity only once.

**SO:**

1. Is it expensive to have a `FixedUpdate()` method that checks for `false` value and returns every frame?
2. Which of the two methods performs better in this case?

# Answer
"Put physics effects in `FixedUpdate`" is talking about *ongoing* effects, not initial setup.

So really, it could be better phrased as "Use `FixedUpdate` *instead of `Update`* for ongoing physics effects"

Just put the initial velocity assignment in `Start`. Test your game. Observe that nothing bad happens.

Note that this caveat also means it's OK to put *instantaneous* effects - like responding to a jump button being pressed - in `Update`. It won't have an impact on the integrated position of the object until the next physics step (unless you're using extrapolation), but that's no worse than queuing-up the input and handling it in the next `FixedUpdate` anyway.
> 1 votes

---
Tags: unity, c#, physics, rigidbody
---


# Question
Title: Code for making Material offset follow Bone transform not exactly working
In my game, I have an Eye Bone that is constantly moving.

I'm trying to make a material attached to the eye (pupil material) move in relation to the Eye bone's transform.

This Script is indeed moving the Material's offset, but it is seemingly ignoring the offsetMultiplier bit. For instance, if I set `offsetMultiplier` to 0, the material offset never equals 0 but instead keeps exactly following the Bone transform numbers.

What might be the mistake here?

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

public class EyeBoneMatOffset : MonoBehaviour
{
    public Transform targetBone;
    public Material mat;
    public float offsetMultiplier = 0.0f; //0 for testing purposes

    // Start is called before the first frame update
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        //Create a vector to offset the material
        var offset = new Vector2(targetBone.transform.localRotation.eulerAngles.x * offsetMultiplier,
                                 targetBone.transform.localRotation.eulerAngles.y * offsetMultiplier);

        //Apply the offset
        mat.mainTextureOffset = offset;
    }
}

```

Script inspector set up:

Edit:

I'm having issues getting the Eye(Pupil) Material to correctly move with the Eye bone movement.

You can see that when I hit play, the script does get the Eye Material to Initially move, but then it is (visually) frozen instead of moving back and forth. The goal is for it to correctly Eye Track the cube.

As a sidenote, for the Eye Material's X and Y offset, the visually correct range of its pupil movement is -0.45 to +0.45 (X), and -0.45 to -0.45 (Y). So it's weird to me that the X and Y offset of the Eye Materials are shown to be moving within that range (which should be good!), yet are not actually moving visually except for when the game first starts.

# Answer
What it was was that the EulerAngles were moving in such tiny increments that they were undetectable. I switched to using the target bone's transform.rotation.x instead, as I am not sure how to correctly use EulerAngles for this issue. If I multiply the EulerAngles by 2, then it still moves the bones by tiny visually undetectable increments of .00001. Really weird.

But- Pseudo-solved by using transform.rotation instead!
> 0 votes

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


# Question
Title: List to hold copies of a prefab for later deletion
I'm working on a game in which obstacles are Instantiated randomly 5 to 20 units ahead of the player.

When they are instantiated, I want to add them to a list so that when there are too many obstacles loaded in the game, it will remove them from the list and then delete them from the game.

I'm having trouble adding them to the list, because using `obstacleList.Add(Obstacles.name);` doesn't work.

Here's my code:

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

public class Generate : MonoBehaviour{

    //player position
    public Transform Player;

    // The prefab for an obstacle
    public GameObject Obstacle;

    // Holds float distance from 0 for each obstacle that is instantiated
    private float nextObstacle = 30;

    // is supposed to hold the names of all active instances of the obstacle prefab
    List<string> obstacleList = new List<string>(10);

    void FixedUpdate()
    {
        //Checks to see if the player is colser than 30 units to the most recently spawned obstacle
        if (nextObstacle - Player.position.x < 30)
        {
            //Generates a new obstacle
            GenerateObstacle();
        }
    }

    void GenerateObstacle()
    {
        // Randomly assignes a number for horizontal and vertical Transform
        int randH = Random.Range(5, 20);
        int randV = Random.Range(1, 3);

        //Instantiates an obstacle using those random values
        Instantiate(Obstacle, new Vector3(nextObstacle + randH, randV, 0), Quaternion.identity);

        //Makes that obstacle the new distance so a new obstacle can be spawned
        nextObstacle += randH;

        // Is supposed to add the name of the obstacle that was Instantiated to a list
        obstacleList.Add(Obstacle.name);

        //checks when list has more than 10 items in it
        if (obstacleList.Count > 10)
        {
            DeleteObstacles();
            // Removes the first item from the list
            obstacleList.RemoveAt(0);
        }
    }
    void DeleteObstacles()
    {
        // Supposed to destroy the copied prefab
        Destroy(Obstacle);
    }
}

```

# Answer
> 1 votes
A `List<string>` is all well and good if you just want names. But you don't want to delete the *name*, you want to delete the *game object*.

Also, if you always want to delete from the start of the collection (First-In, First-Out), and you don't need to traverse or randomly access items in the collection, then the structure you want is a `Queue`.

So, replace:

```
List<string> obstacleList = new List<string>(10);

```

with:

```
Queue<GameObject> obstacles = new Queue<GameObject>(10);

```

Next, capture the newly-created instance when you make it:

```
var instance = Instantiate(Obstacle, new Vector3(nextObstacle + randH, randV, 0), Quaternion.identity);

```

And add it to your queue:

```
obstacles.Enqueue(instance);

```

Your removal can then look like this (put it before you add so you don't exceed your promised capacity):

```
if (obstacles.Count >= 10)
{
    var toBeDestroyed = obstacles.Dequeue();
    Destroy(toBeDestroyed);
}

```

---
Tags: c#, gameobject, prefabs
---


title: Object floating on "top" of tilemap

text:
# Question
Title: Object floating on "top" of tilemap
I've made a character design and added `Rigidbody 2D` and `Box Collider 2D` to it but when I put it on top of the ground which is in tiles in a tilemap it floats on top i.e. the tilemap consists of a hill going up then down but when I put it on the ground it goes up again in a position level to the peak of the hill
and even on top of hill it floats a little above the grid line

# Answer
From an initial look (Thank you for providing pictures), it looks like there is a collider here that we haven't seen yet.

I would recommend:

* Check that the collider for the player is accurate
* Check that the colliders for the ground are accurate
* Give your scene a check to make sure there are no other colliders messing with things.

---

**Edit**

This wasn't the answer, as is evident.

The next thing you should try is checking that both your coin and player are set to be affected by gravity. This can be found in the rigidbody settings.
> 0 votes

---
Tags: unity, rigidbody, collider
---


title: Controlling Source Image From Script

text:
# Question
Title: Controlling Source Image From Script
I am trying to make a health system where hearts display how much health you have. On each heart, I have an Image component. I am trying to control what source image the Image component uses from a script, but it is not letting me. I read the documentation for the Image component here and it has no sprite property. This is my code:

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

public class HeartScript : MonoBehaviour
{
    public GameObject heart1;
    public GameObject heart2;
    public GameObject heart3;
    public Sprite halfHeart;
    public Sprite fullHeart;
    public Sprite emptyHeart;
    private double playerHealth = 3;

    // Update is called once per frame
    void Update()
    {
        if(playerHealth == 2.5)
        {
            heart1.GetComponent<Image>().image = fullHeart;
            heart2.GetComponent<Image>().image = fullHeart;
            heart3.GetComponent<Image>().image = halfHeart;
        }
        else if(playerHealth == 2)
        {
            heart1.GetComponent<Image>().image = fullHeart;
            heart2.GetComponent<Image>().image = fullHeart;
            heart3.GetComponent<Image>().image = emptyHeart;
        }
        else if(playerHealth == 1.5)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = halfHeart;
            heart1.GetComponent<Image>().image = fullHeart;
        }
        else if(playerHealth == 1)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = fullHeart;
        }
        else if(playerHealth == .5)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = halfHeart;
        }
        else if(playerHealth == 0)
        {
            heart3.GetComponent<Image>().image = emptyHeart;
            heart2.GetComponent<Image>().image = emptyHeart;
            heart1.GetComponent<Image>().image = emptyHeart;
        }
    }

    public void RemoveHealth()
    {
        playerHealth = playerHealth - 0.5;
    }
}

```

How do I change the sprite the heart uses from a script?

# Answer
> 0 votes
There are two issues with your script:

1. As @Safa mentioned that the Image has the property of sprit to change the sprite of the image.
2. You are using wrong namespace. Change

> using UnityEngine.UIElements

To

> using UnityEngine.UI

Also, I made some changes to the script for better performance. Reasign value to hear1, heart2, heart3 as I changed it form game object to Image.

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

public class HeartScript : MonoBehaviour
{
    public Image heart1;
    public Image heart2;
    public Image heart3;
    public Sprite halfHeart;
    public Sprite fullHeart;
    public Sprite emptyHeart;
    private double playerHealth = 3;

    // Update is called once per frame
    void Update()
    {
        if (playerHealth == 2.5)
        {
            heart1.sprite = fullHeart;
            heart2.sprite = fullHeart;
            heart3.sprite = halfHeart;
        }
        else if (playerHealth == 2)
        {
            heart1.sprite = fullHeart;
            heart2.sprite = fullHeart;
            heart3.sprite = emptyHeart;
        }
        else if (playerHealth == 1.5)
        {
            heart3.sprite = emptyHeart;
            heart2.sprite = halfHeart;
            heart1.sprite = fullHeart;
        }
        else if (playerHealth == 1)
        {
            heart3.sprite = emptyHeart;
            heart2.sprite = emptyHeart;
            heart1.sprite = fullHeart;
        }
        else if (playerHealth == .5)
        {
            heart3.sprite = emptyHeart;
            heart2.sprite = emptyHeart;
            heart1.sprite = halfHeart;
        }
        else if (playerHealth == 0)
        {
            heart3.sprite = emptyHeart;
            heart2.sprite = emptyHeart;
            heart1.sprite = emptyHeart;
        }
    }

    public void RemoveHealth()
    {
        playerHealth = playerHealth - 0.5;
    }
}

```

I hope this will help.

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


# Question
Title: In practice, is it better to store Euler angles or store three vectors represent as "front/right/up"?
I'm writing a game engine, and when it comes to the transform part, I just use the representation which unity/ue uses, that is: a vector for the position, a vector for Euler angles, and a vector for scale.

But I found that in most cases, I need to deal with the axis of an object, it's much intuitively to use the three axes.

So in practice, is it better to store Euler angles or vectors for axis?

Let me give a example to explain myself: Here's my transform class:

```
class Transform {
 public:
    glm::vec3 position_;
    glm::vec3 rotation_;
    glm::vec3 scale_;
}

```

And each time I want to "move it forward to xxx meters", I need to calculate a front vector, which is a local z axis of the object(I use the term 'local' which comes from blender, the local cooradinate, not sure I make myself clear), what I do is to rotate the (0,0,1) with the Euler angles, to get a vector, which is the "local" z axis of the object.

My question is that is it batter to use the data structure I pasted above, or use there vectors, represent for x,y,z axes for the object?

# Answer
> So in practice, is it better to store Euler angles or vectors for axis?

This totally depends on your requirements. In general, object orientations (rotations) can be represented in several ways: A specific sequence of rotations around the coordinate system axis (for example Euler angles), a rotation axis and a corresponding angle, a rotation matrix (which is basically your tree axis approach), or as a quaternion. There might be other representations but the named ones are the ones I know. Each of those representations can be transformed into the others since they describe the same thing. To decide which one is the best for your use-case you have to know about their advantages and disadvantages.

Euler angles are just three angles that represent a specific sequence of rotations around the coordinate system axis. Since the sequence and axis are defined you only need the three rotation angles (related Wikipedia site). While this is a quite memory-efficient representation, it suffers heavily from the gimbal lock problem (see this link) as soon as you start calculating with them. In short: There are certain Euler angle combinations that align 2 axes with each other so that you lose a degree of freedom. If you write a flight simulator or anything that involves a lot of varying orientations Euler angles are probably not what you want to use (fun-fact: Even though they are suboptimal for flight simulators, they are often used in aerospace engineering). Their advantage is, that they are rather easy to understand, and for angles that are multiples of 45°, you can probably use your hand to simulate the rotations.

The rotation matrix representation is basically what you described with your three axes. In case your 3 vectors are normalized and orthogonal, putting them together (in the correct order) gives you a rotation matrix. Their advantage is that they can be used directly in runtime calculations (matrix-vector multiplication) without further transformations. However, they have 3 times higher storage requirements than Euler angles to represent the same thing. This might be an issue if you are on a tight memory budget and have a lot of objects. Additionally, there are some numerical stability problems due to floating-point errors if you have a constantly rotating object and I was told "renormalizing" a rotation matrix is a little bit more complicated. I can't confirm this since I have never done it myself because I use the next possible representation for that: Quaternions.

Well, quaternions are a little bit hard to describe to someone who doesn't already know them, so just search the internet for more specific information (or look into the answer of DMGregory). They have several nice properties:

* They consist of 4 values, which gives a nice memory footprint and reduces floating-point errors.
* They can be used directly to apply the rotation to a vector
* You can renormalize them easily
* The can be interpolated! - This is a very important property for 3d animations

However, they might be a little bit hard to understand. Also, the quaternion-vector multiplication is a little bit slower than matrix-vector multiplication.

The last representation I mentioned is the axis-angle representation. It just stores an axis in form of a 3d vector and a rotation angle around this axis to describe the orientation of the object. I never used it myself, so read this StackOverflow question for further information about its advantages and disadvantages.

**Summary**

As I mentioned before, all those representations can be transformed into each other and it is your responsibility to use the right one for the operation you want to perform. In the user interface of an editor, Euler angles might be the best representation since they are the easiest one to understand for a user that is not a graphics engine programmer. However, you might want to transform them into a quaternion or matrix as internal engine representation, since you can use them directly for further calculations. If you store the data to a file, you might want to compress a rotation matrix by turning it into a more memory-efficient representation. In general, there is no best way here, you just have to weight computational effort, memory efficiency, and usage comfort of the different representations against each other for your project.

However, as a personal assessment, I think matrices or quaternions are the way to go as an internal storage format for your engine.
> 4 votes

# Answer
Most 3D engines do neither of these things.

Euler angle rotations are very messy to try to compose. If you have one object rotated on all three axes, and you want to rotate it about an arbitrary world axis, the trig gets... yikes. And the result has discontinuities (you have to wrap around from 180 to -180 somewhere) which makes comparing or interpolating rotations more difficult.

Basis vectors are much better behaved, but redundant. If you store all three basis vectors, that's a whole rotation matrix, 9 floats to lug around and update anytime something changes, for something that only really has three degrees of freedom. Multiplying two rotations in this form means 27 multiplication and 18 addition operations. Matrices/basis vectors interpolate a bit better than Euler angles, without discontinuities or gimbal artifacts, but need re-orthonormaliztion to keep them from squashing in transit, and they can't interpolate 180 degrees without special handling.

So the usual internal memory representation for a rotation is a quaternion. A quaternion is 4 floats (a tiny bit heavier than Euler angles, but still lighter weight than 2 basis vectors and less than half the size of a matrix), representing a point on a unit hypersphere with three imaginary coordinates.

You can form a quaternion from an angle and a unit vector axis to rotate around like so:

```
q.w = cos(angle/2f);
q.x = sin(angle/2f) * axis.x;
q.y = sin(angle/2f) * axis.y;
q.z = sin(angle/2f) * axis.z;

```

Composing two rotation quaternions costs 16 multiplies and 12 adds, substantially cheaper than with matrices/basis vectors (and skipping the trig hell of Euler angles), and they interpolate flawlessly over 180 degrees, much more cheaply than the alternatives.

There are downsides: ransforming a vector by a quaternion is slower than with a matrix/basis vectors. So we'll still convert these to a matrix when we expect to do a lot of that.

A transform will usually keep a cached local-to-world matrix (or its inverse), updated lazily when trying to do any vector operations if the source of truth (translation vector, scale triplet, rotation quaternion, and parent transform) has changed in the meantime. We use this cached matrix to furnish fast vector transformations, or upload to the GPU to transform all the vertices in a mesh. But we don't manipulate it as our way to store the object's rotation, and it can be omitted from serialized data since we can rebuild it from the quaternion & co whenever we need.

Now, quaternions aren't the most intuitive to read and manipulate by hand, so engines typically convert them to Euler angles wherever a rotation is displayed to a human user, like in an inspector panel or text format file, or by exposing Euler angle options in the API. But it's still a quaternion under the hood.
> 4 votes

---
Tags: transformation
---


# Question
Title: Given a triangleIndex how do you find the global position of a mesh vertex - Unity
For Unity's mesh system - Given a triangleIndex how do you find the global position of a mesh vertex (of a meshfilter on a gameobject)?

# Answer
```
    // Read the mesh without copying it.
    var mesh = meshFilter.sharedMesh;

    // Cache these if you're going to be querying the same mesh a lot,
    // or use their List overrides to re-use the same managed memory.
    var allIndices = mesh.GetIndices(0);  // 0 = Sub-mesh 0
    var allVertices = mesh.vertices;

    // It takes 3 indices to make a triangle,
    // so the 0th triangle starts at index 0, the next starts at index 3...
    int firstIndexLocation = hit.triangleIndex * 3;
    // (Here I assume you're reading the triangle index out of a raycast hit)

    // Read three consecutive vertex indices,
    // and use them to look up the corresponding vertex, in local space.
    var myVerts = new Vector3[] {
        allVertices[allIndices[firstIndexLocation + 0]],
        allVertices[allIndices[firstIndexLocation + 1]],
        allVertices[allIndices[firstIndexLocation + 2]]
    };

    // Convert your vertices from local space to world space.
    for(int i = 0; i < 3; i++) {
        myVerts[i] = meshFilter.transform.TransformPoint(myVerts[i]);
    }

    // myVerts now contains the three vertices of the hit triangle, in world space.

```
> 1 votes

---
Tags: unity, procedural-generation, mesh
---


# Question
Title: Generated Mesh Does Not Have Shadows/Shading
# Description

I'm trying to create a water shader, and at this point in development I'm using a Photoshop-generated cloud texture as a map for vertex displacement.

The displacement itself works just fine, but there is no shading on the mesh.

**In Game view:**

**In Scene view:**

Without the Point Light, the whole mesh is just a grey blob with detectable shapes only at the edges, where the color intersects with the grey-brown of the background:

# Remarks & Code

Because I need more vertices than the default Plane object has, I decided to generate the mesh inside a script. To do this, I followed Brackeys' tutorial on procedural terrain generation; the mesh generation part.

This includes generating the vertices, the triangles, and the UVs. Here is my code:

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

[RequireComponent(typeof(MeshFilter))]
public class PlaneMeshGenerator : MonoBehaviour {
    public Vector2 squareCount;
    public int resolution = 4;

    [HideInInspector] public Mesh mesh;

    private Vector3[] vertices;
    private int[] triangles;
    private Vector2[] uv;

    private int xSize;
    private int zSize;

    private void Awake() {
        mesh = new Mesh();
        GetComponent<MeshFilter>().mesh = mesh;
    }

    private void Start() {
        xSize = (int)squareCount.x;
        zSize = (int)squareCount.y;

        GenerateMeshData();
        UpdateMesh();
    }

    private void GenerateMeshData() {
        xSize = (int)squareCount.x;
        zSize = (int)squareCount.y;

        vertices = new Vector3[(xSize + 1) * (zSize + 1)];
        triangles = new int[(xSize * zSize * 6)];
        uv = new Vector2[(xSize + 1) * (zSize + 1)];

        #region Generate the Vertices
        for (int i = 0, z = -(zSize / 2); z < zSize / 2 + 1; z++) {
            for (int x = -(xSize / 2); x < xSize / 2 + 1; x++) {
                vertices[i++] = new Vector3(x / (float)resolution, 0f, z / (float)resolution);
            }
        }
        #endregion

        #region Generate the Triangles
        int vert = 0;
        int tris = 0;

        for (int z = 0; z < zSize; z++) {
            for (int x = 0; x < xSize; x++) {
                triangles[tris + 0] = vert;
                triangles[tris + 1] = vert + xSize + 1;
                triangles[tris + 2] = vert + 1;
                triangles[tris + 3] = vert + 1;
                triangles[tris + 4] = vert + xSize + 1;
                triangles[tris + 5] = vert + xSize + 2;

                vert += 1;
                tris += 6;
            }
            vert += 1;
        }
        #endregion

        #region Generate the UVs
        for (int i = 0, z = 0; z < zSize + 1; z++) {
            for (int x = 0; x < xSize + 1; x++) {
                uv[i++] = new Vector2((float)x / xSize, (float)z / zSize);
            }
        }
        #endregion
    }

    private void UpdateMesh() {
        Mesh mesh = this.mesh;
        mesh.Clear();

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uv;

        mesh.RecalculateNormals();
    }
}

```

(You can disregard the `resolution` variable. It just resizes the mesh so I can get more vertices for the same size.)

And here is the shader code:

```
Shader "Custom/Water"
{
    Properties
    {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
        _CloudTex ("Clouds Texture", 2D) = "white" {}
        _Amount ("Displacement Amount", Range(0.1, 5)) = 1.0
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows vertex:vert

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0
        #include "UnityCG.cginc"

        sampler2D _MainTex;
        sampler2D _CloudTex;

        struct Input
        {
            float2 uv_MainTex;
        };

        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
        half _Amount;

        // Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
        // See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
        // #pragma instancing_options assumeuniformscaling
        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void vert(inout appdata_full v, out Input o) {
            UNITY_INITIALIZE_OUTPUT(Input,o);
            fixed height = tex2Dlod(_CloudTex, float4(v.texcoord.xy, 0.0, 0.0)).r;
            v.vertex.xyz += v.normal * height * _Amount;
        }

        void surf (Input IN, inout SurfaceOutputStandard o)
        {
            // Albedo comes from a texture tinted by color
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;
            // Metallic and smoothness come from slider variables
            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

# My Guess

At first I thought the normals had been calculated incorrectly, but I don't think that's the case now. For one, applying an image texture works perfectly fine. And as you can see, I'm using the vertex normals in my shader code for displacement, and that works fine as well.

Cast and Receive Shadows is on, and the Directional Light's culling mask is set to "Everything".

The shader was created as a Standard Surface Shader, not Unlit, so that shouldn't be a problem.

A while ago, I followed the aforementioned tutorial to the fullest, and I didn't have this problem there. The only difference I can see here is that I took the displacement code from the C# script to the shader, meaning I used a different material. However, I don't know how to fix this without reverting to doing this in the script, which I can't do here.

Said old proc. gen. terrain:

# Other

I don't know what Shadowmasks and Shadow Cascades are, but I took pictures anyway, in case they're relevant":

# Answer
The normals are not getting recalculated after the vertex displacement in the shader, which means that the shading is still based on the normals generated during the plane mesh generation.

Recalculating normals in a displacement shader is a whole other problem since you can't simple call something equivalent of `mesh.RecalculateNormals();`.

You can for instance use central differencing to calculate the normals after a texture displacement in a shader. You can see an example of this in the following link and its subsequential links.
> 1 votes

---
Tags: unity, shaders, lighting, shadows
---


# Question
Title: Unity: How can I control a Shadergraph effect on multiple enemies with the same prefab?
So I made a simple White Flash -\> Dissolve effect with shader graph 2D, it's my 1st time using shaders. I'm controlling the effect using a float inside the shader, with:

```
Material.SetFloat("FLOAT_NAME", 0-1f);

```

And I'm wandering how can a control only a single instance of my Shader without affecting all my enemies.

Example: I have 20 enemies, all from the same prefab with the same material. I want to be able to make 1 enemy dissolve whenever I shoot at him.

# Answer
> 0 votes
Not sure how to mark as solved, but my problem was using the wrong reference, I referenced the Material directly, instead of the spriteRenderer material.

---
Tags: unity, shaders, effects, unity-shader-graph, prefabs
---


# Question
Title: How can I position a large amount of boxes to prevent overlap efficiently
I've been working on an asset to position labels like they do in Diablo or Path of Exile, but I'm having trouble finding an algorithm to position the labels efficiently.

Currently I just boxcast in each of the 4 directions until there is no overlap, compare their distances, and take the smallest value to place it, but this just seems too much hassle and too slow with a large number of labels.

Especially when you look at this video clip from Path of Exile without loot filter. There's no way they can iterate over that many labels and place them instantly.

I think they keep some kind of array that says *"there are X open spots for this label group currently, select the nearest one or any"*, and update it when a label gets placed.

I know this question has been asked and I know about automatic label placement etc. but I don't think it really applies in this case. At a certain point it doesn't really matter where the labels get positioned, they just need to be positioned around another label as fast as possible without overlap.

Basically, I'm looking for a way to save occupied/unoccupied space around a label and retrieve that value somehow.

# Answer
Here's a sketch of one solution:

Divide your placement domain into rows, each row the height of a label. (If you have boxes of different vertical sizes this becomes more complicated, but it looks like the majority of items in Pillars of Eternity have very similar heights)

For each row, store a list of labels in that row. Each label knows its center, width, and the target point it's trying to align to.

This lets us greatly simplify the problem into finding a placement in a line, without hitting the full \\$n^2\\$ complexity of checking against every other label on screen.

When you add a new label, round its target point's vertical position divided by the row height to find which row it "wants" to be in.

Try first to place the label in this row.

With a linear or binary search, you can find the first label in the row that belongs to the right of this one / the last label that belongs to the left (based on their respective target positions). If there's no label that belongs to the left or right, you can treat those constraints as infinite.

Check if there's room to place the label between these limits - shifted to bring you as close as you can to your target position. If so, place the label, and you're done.

If not, compute the minimum penetration depth - how much would the other labels need to slide apart to make room? Hang onto that as a score for the disruptiveness of the placement.

Then check the row above/below in the same way, factoring in the vertical shift from where your label "wants" to be as part of their disruptiveness score. You can repeat this out to a controllable maximum vertical displacement. If you find a placement opportunity below a target disruptiveness score, place it. Otherwise, just pick the lowest score you found out of the rows you checked.

If your chosen placement requires sliding, you iterate over the other labels in the row to the left or right of your newly-placed label, shifting them over by the remaining overlap, until no overlap remains.

This approach is \\$O(r \cdot k)\\$ per insertion (or \\$O(r \cdot \log k + k)\\$ if you use binary search), where \\$k\\$ is the number of items in a single row (so, likely in the range of \\$k \approx \sqrt n\\$ where \\$n\\$ is the total number of labels on screen), and \\$r\\$ is the number of rows you check, which gives you a controllable trade-off between placement quality and search complexity. All the steps can be done with simple interval arithmetic, so you don't need to do any boxcasting along the way.
> 2 votes

---
Tags: collision-detection, algorithm, overlap2d
---


# Question
Title: Why are the images distorted in iOS build?
I'm working on a match three game. But, when I generate iOS build, the images are distorted and completely unrecognizable. However, the issue happens only on some systems. I tried it on an iMac running El Capitan and Xcode 7.2, a Mac mini running Mavericks and Xcode 6.1. On these systems, the images were distorted. I tried on another Mac mini running Mavericks and Xcode 6.1 and there was no distortion.

This is how undistorted images look:

And this is how the distorted images look:

I'm clueless as to why this happens. Please provide some help. Thanks

# Answer
> 1 votes
A very old question, but the issue was resolved. The issue was with the iMac used to generate this build. Used a different mac and the build was ok.

---
Tags: unity, xcode
---


# Question
Title: CS0118 framerate is a field but a type was expected
I'm making a mobile game in Unity and I'm trying to write a script that will set the game to either 30 or 60 frames per second based on a public bool, but I am getting error CS0118 on line 12 with

> fps.framerate is a 'field' but a 'type' was expected.

I am pretty new to Unity so I need help with this?

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

public class fps : MonoBehaviour
{
  public fps framerate;

    // Use this for initialization
    void Start ()
    {
    framerate = GameObject.Find("gameSettings").GetComponent<framerate>(); <= error CS0118
    {
      if (framerate == true)
        Application.targetFrameRate = 60;
      else
        {
            Application.targetFrameRate = 30;
            }
        }
    }
  }

```

# Answer
This is a basic syntax error, and the compiler is telling you exactly what you did wrong.

```
framerate = GameObject.Find("gameSettings").GetComponent<framerate>();

```

`GetComponent<T>` needs a *type* passed as its type argument `T`. But `framerate` is not a *type*, it's a *field* (a public member variable). It looks like you meant to write `GetComponent<fps>` here, since `fps` is the name of this class, which is a type.

But even fixing that, this script does not do anything sensible. It looks like you meant to write something more like this:

```
// Classes begin with an uppercase letter.
public class FPS : MonoBehaviour
{
    // You want a boolean variable to control whether to run at 60 FPS.
    // What you had before was an instance of the FPS script, so each script
    // pointed at another copy of the script, with none of them knowing
    // whether 60 FPS was desired.
    public bool use60FPS;

    void Start ()
    {
        // We don't need to do an expensive search through all our GameObjects
        // for one named "gameSettings" then search its components for an "FPS" script.
        // This script that's running this code IS the FPS script. So just use it.

        if (use60FPS == true) {
            Application.targetFrameRate = 60;
        }
        else
        {
            Application.targetFrameRate = 30;
        }
    }
}

```

I strongly recommend working through some more basic programming tutorials until the fundamental syntax of the language makes sense. Questions about programming syntax, that don't require game development-specific expertise to solve, are usually already answered on StackOverflow.
> 1 votes

---
Tags: unity, c#, frame-rate
---


# Question
Title: MonoGame/Xna gamepad inputs and joystick
I've been around xna game development since very recently, and I'm actually developing a sort of Library for my games. But then I want to make an enemy with default Player settings for keys layouts and stuff. I've managed to create one for Qwerty and Azerty but I also want to create one for gamepad Controllers. Here comes the problem. The default XNA Input Framework is very limited (I think) because, from what I saw, it only manages few buttons that do not include Dpad or Joysticks.

So, is there a way to manage them in xna? or do I need an external Library?

Thanks for your help;

# Answer
Turned out I did not searched enough when I posted this, actually there is a way to get sticks and other inputs from your controller.

Here are several things that might help you if you are in situation than I was lately.

With the Microsoft.XNA.Framwork.Input you have these:

```
GamePad.GetState(id).Thumbstick -> this is your sticks

From there you can choose either
GamePad.GetState(id).Thumbstick.Left
or
GamePad.GetState(id).Thumbstick.Right

then you can get from both the X and Y position
GamePad.GetState(id).Thumbstick.Left.X || GamePad.GetState(id).Thumbstick.Left.Y

```

it's all in the default XNA Framework Input.

you can check every states of every inputs after your GetState(id) by simply searching in the variables that the GamePadState class offers.

Have a nice day
> 0 votes

---
Tags: c#, xna-4.0, control, gamepad
---


# Question
Title: Camera Transition between 2 position / rotation, and follow a 3rd target
I have setup a transition of camera between 2 transform, here the result in video: https://youtu.be/rcwQ6KuEfMw

I have the information of the 2 transform: \- position (vector3) \- rotation (Quaternion)

And I do a Lerp, from Position1 to Position 2, and from Rotation1 to Rotation2:

```
Vector3 finalPosition = Vector3.Lerp(previousPosition, nextPosition, evaluateValueLerp);
Quaternion finalRotation = Quaternion.Slerp(previousRotation, nextRotation, evaluateValueLerp);

```

Now the problem is, as you can see in the video: the player target (the car) is lost durring the transition, I would like to keep it always in the view.

How can I manage to do it ?

Thanks you !

# Answer
> 1 votes
I would 'move' the camera as you are doing now, but just use LookAt, or LookRotation, to point at the target. Lerping the transform.position should give you a smooth transition to the camera's rotation anyway, without the need to Slerp, but you could add some damping once you've got it working.

# Answer
> -1 votes
Try this

```
public Transform target;

transform.LookAt(target);

```

attach this to camera

---
Tags: unity, c#, mathematics, camera
---


# Question
Title: Find random point on a circle with a radius of x and the players position as center (unity)
First of all please note that the game is in 3d and **Not 2d**

The image below is seen from above. What I am trying to do is find a random point 2 - 3 meters around the player.

However I am not quite sure how to achieve it:

I have tried the following:

```
Vector3 randomPointOnCircle = Random.insideUnitSphere;
randomPointOnCircle.Normalize();
randomPointOnCircle *= radius;
return randomPointOnCircle;

```

However I am not sure how to set the player as the center?

*Star - Player*

*Square the general ground*

*Circle - A visual representation of where the points should be around the player*

# Answer
This is a trivial application of the unit circle:

```
Vector3 RandomPointOnXZCircle(Vector3 center, float radius) {
    float angle = Random.Range(0, 2f * Mathf.PI);
    return center + new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
}

```
> 1 votes

---
Tags: unity, sphere
---


# Question
Title: How to do collision detection in Unity between Character Controller, Rigidbody Collider and a NavmeshAgent?
I would like to know more about how collision detection works in Unity especially when character controllers and NavmeshAgents get involved.

For example, how can I detect collision between NavmeshAgent and a CharacterController? I have added a sphere collider to my NavmeshAgent, but it doesn't seem to detect a collision unless I set it to "IsTrigger". I have tried OnCollisionEnter(), OnControllerColliderHit() and OnTriggerEnter(). OnTriggerEnter() seems to be the only one that works and only when I enable "IsTrigger".

How come the other two don't work? Shouldn't they? What if I didn't want to make the collider a trigger?

# Answer
So, after some research, debate and thinking, I came to the following conclusions: basically all collisions that aren't charactercontrollers are explained in the documentation.

When a Character Controller gets involved, you can still use the other methods aswell (OnCollisionEnter() and OnTriggerEnter()), provided the other collider suits the conditions (non-kinematic attached rigidbody or an IsTrigger Collider, respectively)

To detect collision between two charactercontrollers, or between a charactercontroller and a rigidbody, you can also use OnControllerColliderHit(), on condition that you are using the intrinsic Move() method.

To detect collisions between two kinematic rigidbodies, you need to enable "IsTrigger" on one of the colliders. If in this case you still want the kinematic rigidbody to push around other objects, you need to add a second collider with "IsTrigger" set to false. This is also how you should detect collision with navmeshagents, since they don't function with non-kinematic rigidbodies.
> 2 votes

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


title: How to adjust texture on a sphere?

text:
# Question
Title: How to adjust texture on a sphere?
As seen, the texture is not adjusted to the sphere. I tried to change alignment, but it still displays multiple sides. How can I fix this?

# Answer
You need to UV unwrap the sphere properly in you 3d modeling software as UV mapping (texture positioning) is baked into the model itself.
> 2 votes

---
Tags: textures, unreal
---