title: Why are my 3ds Max .fbx exports huge?

text:
# Question
Title: Why are my 3ds Max .fbx exports huge?
I've made an animation in 3ds Max and want to export it to `.fbx` and import it into Unity. I've done this once without problems. But this time, my `.max` file is 2,8MB and my `.fbx` file came out a huge 630MB!

There's nothing wrong with my model: I exported it from a Blender model (to `.fbx`) and imported it to 3ds max (converted it to an editable poly) to do my rigging and animation. As soon as I import some `.bip` animations, I get these huge files.

Is there a safe way to get smaller file sizes? I don't mind redoing the rigging if I can solve this.

# Answer
After numerous tests (I tried my model with a number of different animations, I tried this specific animation with different models, I even installed 3DS Max 2014) and trying out different export settings, I figured out what is causing this issue. I don't know WHY it is causing it, I mean it doesn't seem logical to me, but at least I managed to keep my own sanity..

I had my character model as a single mesh and my biped skeleton, but I had kept the eyeballs as a separate mesh, which I had linked to my head bone. The reason I did this, is because I was planning to set some facial rigging afterwards (don't know how easy it is yet, I was going to look through some tutorials later on).

For some reason whenever I choose all my objects (body mesh, bones and eyes linked the head bone) 3DS Max is working like crazy using all my RAM and I get a 600MB+ .fbx file.

The easy way to work around it is to attach the eyes to the rest of the body and export a single mesh with the skeleton. But wouldn't I lose the possibility to rig the face then?
> 1 votes

# Answer
I import a 20MB fbx file to update some animation of a man model, then I export it as fbx but I got a 1GB huge file. The cause is the name of the imported fbx. It got non-English words in it so the 3ds Max were working incorrectly with incompatible words. So if you are living or working in a place where English is not the native language, you should check the file name or even the folder and the path.
> 0 votes

---
Tags: 3dsmax, fbx
---


# Question
Title: TMP Square Characters when adding Chinese
I'm trying to implement Chinese language in my app. But I'm seeing nothing but squares. I've tried to create from file and hex. They can't be added. For example, there are 3000 letters but only 17 are included.

# Answer
> 0 votes
So if you couldn't use hex use custom character

---
Tags: unity, 3d
---


# Question
Title: Why does Google keep rejecting my update for my game?
I'm trying to push an update to my game that is on the Google Play Store. I've submitted the update over 4 times and Google keeps rejecting it due to the type of ads that are being displayed. I'm using Unity Ads and I've disabled all ads that would be inappropriate such as gambling, dating, 18+..etc.

The annoying part is that I have the game already on the store and I never disabled any of the ads or filtered the ads. Unity Ads are an approved service by Google. Is there something that I am missing? I also have a privacy policy in place as well? Is there something that I could do to keep it from getting rejected? How does Google test games or apps for ad content?!

**Update** So I've tired submitting the update over 8+ times and it's still being rejected. I've disabled the banner ads and I've changed the ads to not show ads rated for 5+. I'm at a loss for why it's being rejected. I've emailed Google over it and they just send me the same information they sent when it was rejected the first time. Still no answer..

(https://i.stack.imgur.com/wDlj1.jpg)!

(https://i.stack.imgur.com/OHGPi.jpg)

# Answer
So after getting an email from Google, I figured out that once your APK is rejected, you have to reupload a new APK. I was just trying to adjust the ad content in unity dashboard. So after adjusting the ad content and reuploading a new APK, it was accepted. Thank you for all the help!
> 1 votes

# Answer
If you target for kids or are on the family list you need to exclude anything 13+ or you won't be in compliance. If you swap that and submit you should pass
> 1 votes

---
Tags: google-play, advertisements, unity-ads
---


title: Making an enemy shoot every few seconds

text:
# Question
Title: Making an enemy shoot every few seconds
so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat.

```
//this is the enemy object
 function Enemy(x, y){
 this.sprite = enemySprite;
 this.x = x;
 this.y = y;
 this.shooting = function(){
    while(enemyBullets <= bulletsPerTick){
        var enemybullet = new enemyBullet(this.x , this.y);
        enemyBullets.push(enemybullet);//i'm adding the bullet object to an array .
    }
    for(var i = 0; i<enemyBullets.length;i++){
        enemyBullets[i].show();
        enemyBullets[i].move();//if there is an element in the array , draw and update the bullet.
    }
}// i left only the important elements of the object needed to answer my question
    //this is the enemy bullet object
    function enemyBullet(x, y) {
    this.x1 = x;
    this.y1 = y;
   this.r = 5;
    this.show = function ()
    ctx.beginPath();
    ctx.arc(this.x1, this.y1, this.r, 0, Math.PI * 2);
    ctx.fillStyle = "black";
    ctx.fill();
    ctx.closePath()//drawing the bullet
}
this.move = function () {
    this.x1 = this.x1 - 5;//updating the bullet
}

```

In my main file , i have a function draw() which is in requestAnimationFrame(draw):

```
for (var j = 0; j < enemies.length; j++) {
            enemies[j].show();//here i spawn the enemy sprite
            enemies[j].shooting();//this is the function which adds the bullets to the array , draws them and updates them.
        }

```

Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies\[j\].shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know.

# Answer
> 0 votes
Are you looking for something like setInterval? That would be a very JavaScript-ish way to make a repeating task.

If you want something based on a per-frame basis you'd probably want to have some manual counters increased based on a deltaTime of some sort and reset at some threshold, but I think `setInterval` would be sufficient for your case. Don't forget to keep the `intervalID` returned from `setInterval` so you can `clearInterval` when your enemy dies.

Would something like that help?

---
Tags: javascript, html-canvas
---


# Question
Title: Calling setInterval from requestAnimationFrame causes enemies to shoot continuously
I am making a 2D canvas game in JavaScript. I am trying to make the enemies shoot a bullet every 3 seconds.

```
for (var i = 0; i < enemyBullets.length; i++) {
    enemyBullets[i].show();
    enemyBullets[i].move();
}
// With this loop, whenever there is a bullet added to
// the array , it gets drawn on the canvas and updated.

function Enemy(x, y) {
   this.shoot = function(){
        var ebullet = new enemyBullet(this.x, this.y);
        enemyBullets.push(ebullet);
        // Here I have the enemy object and the function
        // which adds the bullet to the array.
    }
}

```

Here is how I use the `enemy.shoot` function in the `draw()` function, which is called via `requestAnimationFrame()`:

```
function lol(){
    for(var v = 0; v<enemies.length;v++){
        enemies[v].shoot();
    }
}
setTimeout(lol,3000); // This is what I've tried so far

```

When I do this, the enemies are not shooting a single bullet every 3 seconds as desired. Instead, 3 seconds after the beginning of the program, they start adding infinite bullets to the array and I don't know how to handle it.

# Answer
Use `setInterval` instead This will make the function get called multiple times.

The other option is to put a `setTimeout` call inside the `lol` function so it will be rescheduled.

To stop the scheduled call you can pass the return value of the `setInterval` or latest `setTimeout` to `clearInterval` or `clearTimeout` resp.
> 0 votes

---
Tags: javascript, html-canvas
---


# Question
Title: How can I compare two quaternions for logical equality?
I'm trying to write some unit tests and realize I don't know how to compare quaternions. I need to know if two quaternions represent the same orientation (the object would be facing the same way). With a vector like position I'd simply compare the parts and check they are close enough, but for quaternions the values can be very different.

How can I compare two quaternions?

# Answer
> 14 votes
If your two quaternions are `q1` and `q2`, they represent the same rotation if either of these two conditions hold:

1. `q1` is component wise approximately equal to `q2` OR
2. `q1` is component wise approximately equal to `-q2`

Knowing this, you can write a fairly simplistic equality tester that suits your goal.

# Answer
> 16 votes
Just because it hasn't been mentioned. Since quaternions used for spatial orientation are always unit length (or should be), the following will also work.

$$\lvert q\_1 \cdot q\_2 \rvert \> 1 - \epsilon$$

where \\$\epsilon\\$ (epsilon) is some fudge factor to allow for small errors due to limited floating point precision. If (and only if) both quaternions represent the same orientation then \\$q\_1 = \pm q\_2\\$, and thus \\$q\_1 \cdot q\_2 = \pm 1\\$. If you want to make sure they're the same rotation (rather than just orientation), then remove the absolute value.

# Answer
> 2 votes
Quaternions are stored as 4 floats or doubles, often called x, y, z and w, where the first three represent an axis and w the degree of rotation around that axis.

A naive approach would be to just compare those numbers of two quaternions for equality. However, because floating point calculations involve an error, you should at least use an error, often called eps (for epsilon) and compare each component like

```
    double const eps = 1e-12; // some error threshold
    abs(quat1_x - quat2_x) < eps // similar enough?
    // repeat for other values..

```

A better test would be to calculate the dot product of the two quaternions and test whether it is close to 1.0. You should look up the equation of quaternions with sin and cos and just dot two quaternions, then you should readily see why this works.

# Answer
> 1 votes
Based on all the suggestions to use Dot and eps I found that using (in unity):

```
Mathf.Approximately(Mathf.Abs(Quaternion.Dot(transform.rotation, to)), 1.0f)

```

worked well without me having to make a decision for the size of eps.

---
Tags: mathematics
---


title: Unity Shader Blend like ugui Outline

text:
# Question
Title: Unity Shader Blend like ugui Outline
Unity UGUI `Outline` it create fourfold vertexs, So I wirte shader to optimization ( vertex only create once ), And I want to Keep one pass . (one drawcall)

There are four character , all character font size are same. but this character edge look a little small.

I write shader like this

```
 fixed4 frag(v2f IN) : SV_Target
        {
            fixed4 color = (tex2D(_MainTex, IN.texcoord) + _TextureSampleAdd) * IN.color;

            float4 pClipRect = float4 (IN.uvOriginXY, IN.uvOriginZW);
            color.a *= IsInRect(IN.texcoord, pClipRect);
            half4 val = half4(_OutlineColor.r, _OutlineColor.g, _OutlineColor.b, 0);//(r,g,b,0)

            //black characters
            val.a += SampleAlpha(2, IN);
            val.a += SampleAlpha(5, IN);
            val.a += SampleAlpha(8, IN);
            val.a += SampleAlpha(11, IN);

            val.a = clamp(val.a, 0, 1);

            //blend
            color = (val * (1.0 - color.a)) + (color * color.a);

            return color;
        }

```

And the lower right picture is create by UGUI `Outline` it look like white color overlap black color , How can I do like this ?

The problem probably from here : `color = (val * (1.0 - color.a)) + (color * color.a);`

What should I do to make it look like UGUI`Outline`? thanks.

# Answer
> 1 votes
Thanks @Draco18s suggest , I think I Slove this problem , this problem is a about alpha value missing. So just choose the larget alpha. like this:

```
            half orginA = color.a;
            color = (val * (1.0 - color.a)) + (color * color.a);
            color.a = max(orginA,val.a);// choosing larger one

```

---
Tags: unity, c#, shaders, alpha-blending
---


title: Tiles on sphere - check visibility

text:
# Question
Title: Tiles on sphere - check visibility
I have a sphere with tiles. I need to check if a tile is visible or not. See the image. Tiles are red squares, "screen" is represented by yellow quad.

Currently, I calculate coordinates of tiles in spherical coordinates, convert them to Cartesian and project them from world to screen space. This works only partially (the missing tiles are correctly removed). However, this process has several false positives. For example tile in blue quad should not be visible, but its screen space bounding box overlaps with my virtual "yellow screen" =\> tile is visible.

How do I solve this problem correctly?

# Answer
> 0 votes
You can use frustum culling to eliminate entities from the render queue based on the geometry. This will help reduce false positives as well as reduce the need to convert the geometry to screen space.

There is a good tutorial on how to implement view frustum culling here http://www.lighthouse3d.com/tutorials/view-frustum-culling/

---
Tags: projection, sphere, visibility-determination
---


# Question
Title: bullet raycast vehicle - understanding coordinate system
Bullet world space coordinate system is the same as opengl world coordinate system. I have noticed that raycast vehicle has the following function:

```
virtual void btRaycastVehicle::setCoordinateSystem(int rightIndex,
                                                   int upIndex,
                                                   int forwardIndex)

```

How does that function work ?

By default raycast vehicle has the following parametets:

* forward vector: \[0, 1, 0\]
* forward axis: 1
* right axis: 0
* up axis: 2

Does it mean that y axis is swapped with z axis ?

After calling:

```
raycastVehicle.setCoordinateSystem(0,1,2);

```

I get the following parameters:

* forward vector: \[0, 0, 1\]
* forward axis: 2
* right axis: 0
* up axis: 1

which makes more sense to me but I'm still confused why a default setup is other (not compatible with world coordinate system) and how to interpret it.

# Answer
> -1 votes
this is Left-hand Rule or Right-hand Rule, that will Affects the direction of the rigid body, you can set value to try.

---
Tags: bullet-physics
---


# Question
Title: How to reference nameof private serialized field in unity custom inspector
I'm running into a problem that I think will seriously affect maintainability down the road, so I'd like to figure it out now before it becomes a problem.

I've been starting to use private \[SerializeField\] rather than public fields to avoid other scripts manipulating internal data.Then, for scripts referencing the component's fields through properties in an interface.

So in a MonoBehaviour I have something like:

```
[SerializeField]
private float speed;

public float Speed => speed; //implements interface

```

However, In my custom inspectors, I now can't use

```
serializedObject.FindProperty(nameof(MonoBehaviourScript.speed));

```

This is because it doesn't have access to the private member speed. I now have to reference it by string name:

```
serializedObject.FindProperty("speed");

```

This worries me since now I can't easily rename the `speed` field. Also, Making both `speed` and `Speed` public is scary since then speed can be manipulated from outside.

Is there a good way to protect myself from external modification, while keeping refactoring easy?

# Answer
> 3 votes
# Use your interface

Handily enough, you already have your answer. Leave the `speed` field public, but never pass around or declare references to that class. Only ever use the interface it implements.

“But wait!” you say. “This doesn’t stop me from shooting myself in the foot!”

Well, no. It doesn’t. You could still sneak around this by declaring a reference to that class *anyway*. You could give the class a name that implies it should not be used, but that reeks of code smell. If you want to be very strict about this, you could declare your class to have internal protection (i.e. not public) and compile it as a separate assembly. Probably not necessary.

There are many other options that don’t work well within Unity regarding the inspector.

Another alternative would be to publicize the names of editable fields from within the class itself, still using `nameof`. Ugly, but possible, and retains encapsulation at the cost of simplicity, requiring essentially declaring every field twice, but hey, you can rename it just once!

```
public class MyMonoBehaviour : MonoBehaviour, IMyMonoBehaviour {
    [SerializeField]
    private float speed; //can rename to your heart’s content, as long as you use a FormerlySerializedAs attribute.
    public float Speed => speed;

    #if UNITY_EDITOR
    public static class FieldNames {
      //actual name of this property is irrelevant. Refactoring it does not affect the field name inside the MonoBehaviour, and vice versa.
      public static string Speed => nameof(speed);
    }
    #endif
 }

```

And to use it:

```
serializedObject.FindProperty(MyMonoBehaviour.FieldNames.Speed);

```

Another alternative is to have the editor be a nested class:

```
#if UNITY_EDITOR
using UnityEditor;
#endif

public class MyMonoBehaviour : MonoBehaviour, IMyMonoBehaviour {
    [SerializeField]
    private float speed; //don’t forget the FormerlySerializedAs attribute if you rename this.
    public float Speed => speed;

    #if UNITY_EDITOR
    [CustomEditor(typeof(MyMonoBehaviour))]
    public class MyMonoBehaviourEditor : Editor{
        public override void OnInspectorGUI() {
            serializedObject.FindProperty(speed); //or MyMonoBehaviour.speed if you want to be more explicit
        }
    }
    #endif
 }

```

If you are worried about having the editor in the same file as the implementation, they could be separated into distinct files using partial classes. Note that both files would still need to be in the same assembly (meaning neither file can be in an editor folder):

MyMonoBehaviour.cs:

```
 public partial class MyMonoBehaviour : MonoBehaviour, IMyMonoBehaviour {
    [SerializeField]
    private float speed;
    public float Speed => speed;
 }

```

MyMonoBehaviourEditor.cs:

```
#if UNITY_EDITOR
using UnityEditor;

public partial class MyMonoBehaviour : MonoBehaviour, IMyMonoBehaviour {
    [CustomEditor(typeof(MyMonoBehaviour))]
    public class MyMonoBehaviourEditor : Editor{
        public override void OnInspectorGUI() {
            serializedObject.FindProperty(speed);
        }
    }
}
#endif

```

Note: I have not tested the above myself. It may not be possible to have nested classes be editors, or it may be possible to have the MyMonoBehaviourEditor class be private and still function correctly. If you try this out, feel free leave a comment or update the answer.

---
Tags: unity, editors, serialization, monobehaviour, refactoring
---


# Question
Title: How to handle MANY enemies in networked P2P game?
Let's suppose a game of 4 players, one is the host.

They will fight many enemies, along the lines of 20-40 at the time. Among other things like sending their own state to the other players (position, rotation, shot this frame, crouched, etc). How do I handle the enemies?

Do the host "decides" the enemies state? (again position, rotation, isattacking, etc). And then sends several messages to the other players so they sync their own game? or do I "divide" the enemies, lets say 40, and 4 players, 10 enemies "controlled" by each player game? and then, each player sends those messages to the other players so all enemies are in sync?

Also, should I group the messages and send one big message instead of 40 little ones? How do I know how big can the message be (how many enemies info in each message)?

Basically I'm asking whats the best way to handle a 4 player p2p game with many enemies on screen.

Any good tip is appreciated.

# Answer
> 1 votes
> Do the host "decides" the enemies state?

This is one way to do it. Which I recommend, but there might be games which work with other methods.

> Basically I'm asking whats the best way to handle a 4 player p2p game with many enemies on screen.

There is no best way.The simplest way to do it would be to have one host control everything about the game, and all other players are the clients which just get that information from the host. Additionally you can have the clients try to "predict" the enemies movement, until the actual position it gotten from the server.

Depending on the game, other ways might be better. It's impossible to tell that unless we know more about the game you are making.

> Also, should I group the messages and send one big message instead of 40 little ones? How do I know how big can the message be (how many enemies info in each message)?

When it comes to sending messages, the general idea is, its better to send one big message, than several small ones. Sending a message over the network has some overhead which multiplies every time a new message is being sent/received.

---
Tags: networking, multiplayer, peer-to-peer
---


title: RayCast node always return null

text:
# Question
Title: RayCast node always return null
I'm using RayCast node to check the object is grounded. Here's the setting:

RayCast node is placed near by ground and the length enough to collide with ground. Also RayCast node is enabled.

RayCast node is child node of FPSController node, and here's the code of FPSController that processing grounded logic:

```
onready var ground_check_raycast: RayCast = $GroundCheckRayCast

func _physics_process(delta):
    process_grounded(delta)

func process_grounded(delta):
    var hit_collider = ground_check_raycast.get_collider()
    print(hit_collider)

```

When I run the game, first few times it return floor, and then immediately return false and never return floor back.

```
** Debug Process Started **
OpenGL ES 3.0 Renderer: GeForce GTX 1070/PCIe/SSE2
[StaticBody:1140]
[StaticBody:1140]
[StaticBody:1140]
[Object:null]
[Object:null]
[Object:null]
[Object:null]
...

```

I have no idea why this won't work. Is there a something that I missed?

P.S. Floor object has static body and CollisionShape. P.P.S. Using Godot 3.1.1

# Answer
Moved RayCast node slightly up, now it works. Still wondering why this won't worked, but it solved anyway.
> 0 votes

---
Tags: raycasting, godot
---


# Question
Title: Can't open nor install 2D Sprite Editor through package manager
In unity `2019.2.10f1 Personal edition` on `Windows 10` I wish to edit a spritesheet through the built-in sprite editor. When I click on the "Sprite Editor" button I get a popup that says

> No Sprite Editor Window registered. Please download 2D sprite package from Package Manager.

(Fig 0)

Attempting to follow these instructions I opened the package manager (fig 1) but couldn't find an install button for the "2D Sprite" package (fig 2).

I searched on the internet if there was any way to manually download it but couldn't find any matching package.

Is this a bug, why can I not install this package ?

(fig 0)

(fig 1)

(fig 2)

# Answer
> 1 votes
It's a sneaky discrete button hidden on the bottom right of that editor window ;) you'll find it hidden there.

---
Tags: unity
---


# Question
Title: How can I make my race game fair with all players and keep it climatic?
I'm making a minigame where up to 5 players have to race against AI or another player(the "enemy"). The race consists of prompts, the current player is asked to press a key in a given amount of time to make progress, if they fail they have to wait until it's their turn again to progress. The current player has to avoid being outran by the enemy they race against, else it's a game over for them.

My problem comes with the fairness of it, the turns are a plain cycle and feels boring, the enemy is dumb and always loses. The game is anticlimatic this way, so I'm looking for a way to choose the next player in a random way but at the same time being fair with the rest until a certain point(the difficulty defines how many consecutive rounds a player can take). I'd also like the game to give random 'boosts' to the players that are near the enemy(and also give the enemy a boost to make it challenging).

How can I achieve this? I'm using Python but I don't know if that matters.

# Answer
> 1 votes
So you have a "one-button" gameplay and it's not engaging enough? Have you played NFSU? It had a drag race mode, which is basically pressing one button in perfect timing to outrace other competitors.

Why not try to replace turns with cooldowns. Whenever someone's cooldown reaches zero - they can have their turn and try to press the button in perfect time. The closer they are to the sweet spot, the less cooldown they'll get. You can adjust the difficulty by making a sweet spot wider or narrower making it less or more hard to hit.

# Answer
> 0 votes
If you are trying to keep the number of turns per player close to equal while making the order random, you could try a couple things:

## 1. Randomize the order of turns each round.

For each round of play, create a random ordering for the group of players you have. They all play through, and then for the next round you create another random ordering. So each player plays once each round, but you don't when in the round you'll play. You might get a player playing twice in a row, but only if they happen to be at the end of one round and the beginning of the next.

In Python, you could do that like this:

```
import random
random.seed()

player_list = ['Daniel Casares', 'pladams9', 'Mario', 'Computer 1', 'Computer 2']

while(!game_over):
  # Runs each ROUND
  random.shuffle(player_list)

  print(player_list)
  # Possible output: ['pladams9', 'Computer 1', 'Daniel Casares', 'Computer 2', 'Mario']

```

## 2. Randomize the choice of next player in an inversely proportional way.

For each turn, pick a random next player, **but** make their chance of going inversely proportional to the number of turns they've already had. By simply making a random choice, each player's expected number of turns would already be equal, but this method discourages runaway streaks where one person gets several turns in a row. Streaks are still possible though, so a single player could get multiple turns in a row.

One way in Python:

```
import random
random.seed()

player_list = ['Daniel Casares', 'pladams9', 'Mario', 'Computer 1', 'Computer 2']
player_turns = {player:1 for player in player_list} # Starting at 1 to avoid division by 0

while(!game_over):
  # Runs each TURN
  next_player = random.choices(
    population=list(player_turns.keys()), # All our players
    weights=[1/turns for turns in player_turns.values()], # 1 divided by the number of turns each player has had
    k=1)[0] # We only want one choice, so k=1; choices() returns a list, so we just take the first value
  player_turns[next_player] += 1 # Increment that player's turn count

  print(next_player)
  # Possible output: 'Computer 2'

```

For more information on random.shuffle and random.choices, you can check out: https://docs.python.org/3/library/random.html

---
Tags: game-design, algorithm, ai, python, random
---


# Question
Title: Wait for vSync without swapping buffers with SDL
I am trying to optimize my SDL rendering loop for an immediate mode GUI application that doesn't need to be redrawn every frame. I have vSync turned on and would like to skip buffer clearing / drawing altogether if the GUI hasn't changed.

The problem is, swapping buffers without redrawing causes flickering because of double / triple buffering. On the other hand, also skipping the buffer swap causes the program to run full throttle because the waiting is effectively done in `SDL_GL_SwapWindow`.

Ideally I would need some kind of function that waits for vSync without swapping buffers, but I haven't seen one in the SDL documentation. I've tried the following solutions but none are satisfying:

* Drawing VBOs every frame even if they haven't been updated. That will reduce load on the CPU but not on the GPU, so not ideal.
* Keeping track of which backbuffers are up to date, and only redraw them if they are dirty. This worked in my testing but requires to make some assumptions (the number of backbuffers, and hoping the driver didn't replace them with fresh ones). So not reliable enough.
* Manually waiting with a small delay. Probably the most reliable, but still not ideal.

# Answer
VSync is done fully by the GPU. Available only through the use of GAPI to be only used internally by driver's GAPI implementation. There is no regular way you can get access to the VSync signal manually.

Manual framerate restriction is not same thing as VSync, however, because it will cause tearing, while VSync is synchronized with refresh rate of the monitor/GPU.

What I suggest you to do instead is to use framebuffer to draw GUI once when needed (is it really that expensive to update GUI every frame?) and then drawing static image from the framebuffer, when backbuffer has to be redrawn. (For messages like `SDL_WINDOWEVENT_EXPOSED` or `SDL_WINDOWEVENT_RESIZED`)
> 1 votes

# Answer
You can use `SDL_GL_SetSwapInterval(0)`.

Parameters:

* 0 for immediate updates
* 1 for updates synchronized with the vertical retrace
* -1 for adaptive vsync
> 1 votes

---
Tags: sdl2, vsync
---


title: Get project's gravity value in Godot

text:
# Question
Title: Get project's gravity value in Godot
I need to get access project's gravity value which set in Project Settings -\> Physics -\> 3D -\> Gravity, however I couldn't find any related information about this.

How do I get project's gravity value in GDScript? In Unity, it can be done by simply Physics.gravity, but in Godot, couldn't find similar.

Using Godot 3.1.1

# Answer
> 1 votes
You can access all project settings through the `ProjectSettings` object.

Note that the *effective gravity* on an object may be different from this value, as `Areas` can override gravity. You can access the gravity affecting an object at a given point in time via `PhysicsDirectBodyState.total_gravity`. `PhysicsDirectBodyState` can be accessed from `_integrate_forces` as well as some physics-related callbacks.

---
Tags: physics, godot, gdscript
---


# Question
Title: Actual Sizes of An Image loaded with a Path
I have a method which selects an Image from device. I need to show this image to users.

The codes below works fine, does what I need.

```
    Texture2D texture = new Texture2D(512, 512);
    texture.LoadImage(System.IO.File.ReadAllBytes(imgPath));
    texture.Compress(false);
    texture.Apply();

```

I just want to know how to change `new Texture2D(512, 512)` to real size of this Image.

Maybe this: `new Texture2D(img.ActualWidth, img.ActualHeight)`

Any idea?

Additionly is there any way to get original width and height from an Image loaded from a `base64String` ?

```
    byte[] imageBytes = Convert.FromBase64String(base64Str);
    Texture2D textureImage= new Texture2D(**250, 300**);
    textureImage.LoadImage(imageBytes);

```

# Answer
When you use LoadImage it resizes the texture for you. It could just as easily be `new Texture2D(2,2)`.

Also note that you don’t need to explicitly call compress or apply if you create the texture with the dxt format to begin with:

```
//Use DXT5 for images which may have an alpha channel, or DXT1 for images that do not have one:
Texture2D texture = new Texture2D(2, 2, TextureFormat.DXT5);
texture.LoadImage(System.IO.File.ReadAllBytes(imgPath));
//No need to call compress or apply here

```
> 0 votes

---
Tags: unity, unityscript, image
---


# Question
Title: Unity ball hitting paddle not reflecting right away
After the ball hits the paddle it continues for a frame or two in the physics, reflected direction, then my `onCollisionEnter2D` function runs and changes the velocity. At least, that's what it seems like. I'm a noob with Unity so I must be misunderstanding something.

https://streamable.com/ac2gg

```
if (other.gameObject.CompareTag("Paddle"))
    {
        float dist = ballRb.transform.position.x - paddleRb.transform.position.x;

        if (dist > 0)
        {
            print("right");
            ballRb.velocity = new Vector2(4, speedY);
        }
        else
        {
            print("left");
            ballRb.velocity = new Vector2(-4, speedY);
        }
    }

```

Thoughts on why there's a stutter after a redirection? I slowed it down so you can see better what's happening.

# Answer
> 2 votes
Great work on your code so far, it's not far off the solution.

One issue you are having is the bounce is applied twice. That is if it's positioned and timed right you'll bounce left and right. The other is physics is processing the bounce first which is off course from your fixed direction.

*Note: For correctness I must mention setting velocity isn't the recommended method, though certainly makes it easier, and with fixes below it works as intended. This could be done by rotating a separate collider/rigidbody around a ray cast intersection to form the bounce surface invisible from the sprite, though that's another question.* ***EDIT: I've added code for this at bottom of answer.***

### Fixes

1. Add a boolean for rebounding while colliding
2. Check/set rebounding
3. Tick "is trigger" on the Paddle Collider (Remove physics)

While that may seem straight forward, there's more to it. I took the liberty of writing an example:

```

public class BallVelocity : MonoBehaviour
{
    // Ref to rigidbody
    private Rigidbody2D m_BallRigidbody2D;

    // Ball Collider
    private Collider2D m_BallCollider;

    // Fixed Velocity on the Y axis to rebound with
    public float VelocityY = 4f;

    // Store these for use each fixed update
    private Vector3 m_NewVelocityLeft, m_NewVelocityRight;

    // Store if we have rebounded this collision
    private bool m_Rebounding = false;

    // need empty start for enable checkbox in editor
    private void Start()
    {

    }

    void Awake()
    {
        // Set references to require components
        m_BallRigidbody2D = GetComponent<Rigidbody2D>();
        m_BallCollider = GetComponent<Collider2D>();

        // Allocate once to prevent GC, however if values are to be calculated, move to FixedUpdate
        m_NewVelocityRight = new Vector2(4, VelocityY);
        m_NewVelocityLeft = new Vector2(-4, VelocityY);

        GetComponent<Rigidbody2D>().velocity = new Vector2(4, -VelocityY); ;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        // Manually check we have collided with paddle
        if (collision.gameObject.tag == "Paddle")
        {
            // Check we are not currently rebounding (still touching collider after last)
            if (!m_Rebounding)
            {
                m_Rebounding = true;

                float dist = transform.position.x - collision.transform.position.x;

                if (dist > 0)
                {
                    print("right");
                    // Set velocity once only in fixed update
                    // This is so other standard collisions will work, i.e. walls
                    m_BallRigidbody2D.velocity = m_NewVelocityRight;
                }
                else
                {
                    print("left");
                    m_BallRigidbody2D.velocity = m_NewVelocityLeft;
                }
            }
        }

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.tag == "Paddle")
        {
            // If not touching then we're clear of rebounding
            m_Rebounding = false;
        }
    }
}

```

Thrown together test: https://streamable.com/d3iyn

To complete my answer with a method of rotating the paddle collider for the physics to process the bound I have created a project and Tutorial.

Project on GitHub: https://github.com/Sibz/PaddleGame

Tutorial on YouTube: https://youtu.be/Vu0hSTDLuhk

And here's the code to go on the paddle. However you need to set up the scene correctly.

* Set Preferences -\> Physics2D -\> Velocity Threshold to 0.0001
* Set Collider of paddle to be trigger, really thin and along top of paddle.
* Put this paddle on it's own layer and set `PaddleLayer`
* Add a second 'invisible' Paddle with collider/rigidbody and set `PaddleCollider`

public class Paddle : MonoBehaviour
{
    public GameObject Ball;
    public GameObject PaddleCollider;

    public float RayDistance = 1;

    public LayerMask PaddleLayer;

    [Tooltip("Max angle of paddle collider change when hitting the very end of the paddle.")]
    [Range(1, 90)]
    public float AngularChange = 45;

    private Rigidbody2D m_BallRigidBody2D;
    private SpriteRenderer m_PaddleSpriteRenderer;
    private void Start()
    {
        m_BallRigidBody2D = Ball.GetComponent<Rigidbody2D>();
        m_PaddleSpriteRenderer = GetComponent<SpriteRenderer>();
    }

    private void FixedUpdate()
    {
        //Get the direction the ball is travelling
        //This is basically the velocity, however we normalize this
        Vector2 direction = m_BallRigidBody2D.velocity.normalized;

        //Ray cast towards the paddle
        RaycastHit2D hit = Physics2D.Raycast(Ball.transform.position, direction, RayDistance, PaddleLayer);

        // Draw a ray we can see in scene view
        Debug.DrawRay(Ball.transform.position, direction * RayDistance, Color.red);

        if (hit)
        {
            PaddleCollider.SetActive(true);

            // Reset our paddle collider so it is flat and at position of paddle
            PaddleCollider.transform.rotation = new Quaternion();
            PaddleCollider.transform.position = transform.position;

            // If we have hit we want to rotate the ball around that point
            Vector2 hitPoint = hit.point; // Worldspace

            // Transform above into local space for the paddle
            // so we can figure how far along paddle hit was
            Vector2 localHitPoint = hitPoint - (Vector2)transform.position;

            // Calculate the offseet on the paddle that we hit
            // this will be -1 to 1, with 0 being centre;
            float offset = /*point.x / length*/ localHitPoint.x / (m_PaddleSpriteRenderer.bounds.extents.x);

            // Get our incoming angle
            // -180' to 180'
            var incomingAngle = Vector2.SignedAngle(direction, Vector3.down);

            // Calculate our angularchange based on hit position
            float adjustedAngularChange = -AngularChange * offset;

            // We want to translate the incoming angle based on the offset
            // but if it's a really shallow angle, bounce it more upwards.
            // (This is to prevent overly sideways movment)
            // Setting the paddle to half incoming angle will reflect directly up
            // so we use this for our corrective figure
            float correctionForShallowHitsAngle = -incomingAngle / 2;

            // Now we can get a value between to two based on how
            // sideways the ball in coming in from
            // if its 90' then 100% use the correctionForShallowHitsAngle
            // if it's 0' then 100% use the adjustedAngularChange
            // we can use linear interpolation (lerp) for this.

            float computedAngularChange =
                Mathf.Lerp(adjustedAngularChange, correctionForShallowHitsAngle, Mathf.Abs(incomingAngle) / 90);

            // Rotate around hit point with angle adjusted by above percent
            PaddleCollider.transform.RotateAround(hitPoint, Vector3.forward, computedAngularChange);

        }
        else
        {
            PaddleCollider.SetActive(false);
        }
    }
}

```

# Answer
> 2 votes
This looks like the result of the discrete way game physics get simulated.

Here's a rough breakdown of what the steps might look like under the hood.

In the first three panels, you can see the ball approaching the paddle. Each physics step, it moves to a new position given by its velocity multiplied by your fixed time step (shown here in purple)

In the third panel, we can see that the ball's new position overlaps the paddle.

To fix this, the physics engine computes the minimum separation vector - the smallest amount it would need to move one (or both) objects in order to resolve the penetration. Here, that offset takes the ball straight up - out of its original line of travel. The physics engine also computes a separating impulse and uses that to modify the ball's velocity. You can see these changes in the 4th panel.

All this happens during the internal physics update step. Any collision pairs detected in this way are queued-up, for their collision/trigger event functions to be called after the physics update is complete.

That's what happens in the 5th panel: your script runs and modifies the velocity to point in the new direction, but it doesn't undo the offset applied by the physics engine to resolve the overlapping colliders.

The change in velocity you've applied won't be visible until the next physics step, so if a frame is rendered at this moment it might look like the ball slid sideways or hesitated on contact with the paddle, before bouncing away.

Lastly, in the sixth panel, we see the effect of the next physics update. Your ball starts moving along the new velocity vector you've set in your script. But because of the corrective offset applied earlier, it's now travelling along a path slightly shifted from the one it came in on.

---

So, what can we do about it?

If you don't want the physics engine to resolve penetrations for you, you can set one or both colliders' `IsTrigger` property to `True`. This will still generate events for your scripts to act on - you'll just have to listen for `OnTriggerEnter2D` instead of `OnCollisionEnter2D` \- but it won't apply any physics impulses or restitution offsets, leaving you in full control.

You can use raycasts or shapecasts to determine the exact moment the ball would have struck the paddle, and scale the offset according to how much "spare change" time was left in the frame after that moment, so you see the new direction of bounce immediately.

You can also enable interpolation or extrapolation on the ball's rigidbody, to generate intermediate display positions based on its movement history or velocity respectively, to smooth its displayed motion and avoid choppiness or apparent hesitation due to the mismatch between the physics timestep and rendering framerate.

# Answer
> 1 votes
It seems that you are running your physics scene in a lower frame rate.

In project setting-\>physics setting, try a larger physics frame rate and it should work fine.

---
Tags: unity
---


# Question
Title: How is tile offsetting accomplished in 2d side scrollers?
The idea is to work with tiles that together make up a larger image, or world so to speak.

but im confused as to what the methods used are to offset the tiles, and whether is a good idea to draw offscreen.

For example

```
var backgroundScroll = 0
update() {
 backgroundScroll++
}
render() {
graphics.draw( resource: BACKGROUND, screenX: -backgroundScroll, screenY: 0)
}

```

while there's no tiles seen here for the sake of simplicity, im simply emphasizing that we are drawing off screen.

As such the question is, how is this background offsetting accomplished, more specifically, without trying to render outside of the screen, as the framework may or may not know how to handle drawing to areas beyond that of the screen.

In essence the game's world will be comprised of an array of tiles

```
var cells[map_w][map_h]

```

and each cell is 32 px wide and 32px height

the idea is to scroll the map but cutting corner cells 1px per unit of speed, but altering the logic so that no negative numbers are entered into the draw function.

I could probably figure something out on my own but i really want to hear how other people are accomplishing this rather popular task

# Answer
If you know where your camera is and the dimensions of your screen you can extrapolate a "cull bounds" in world space. Then, given a function that can check if two rectangles are intersecting, it's a matter of looping through every tile in the map and checking when the tile bounds and cull bounds intersect. Followed by adding the tile verts to a set of verts to be drawn. You can further reduce the verts drawn if the tile type (invisible/sky/etc) doesn't need to be drawn even though it's "in view."

This has an added advantage of making a world of thousands of tiles be one draw call.

EDIT:

> i got confused in this aspect. It's not tremendously hard to set up a srcRect from a bitmap generated from all the tiles merged together.

Generating a bitmap the dimensions of the map multiplied by the tile dimensions will quickly cause problems due to GPU memory exhaustion or too-large texture dimensions as defined by the hardware. The above method will create a single mesh just big enough to be visible on screen.

> Yet, i can't wrap my head around how to accomplish this while maintaining internal TileData structure. I mean theoretically if the tile is 32px wide then if the character had pressed the key long enough it would increment the x cell position accordingly. but im looking more into relating the x position of the character with the tile asociated with that x position. I haven't ventured deep , altough last time i did it i ran into problems offseting tiles

Are you trying to implement tile-based movement (think Rogue-likes) or free-movement with tile-based maps?
> 0 votes

---
Tags: c++, lua, tiles
---


# Question
Title: How should I resolve saved game(cloud saved progress) conflict with local game progress?
I am using play game services and decided to create a small progress manager which will protect user progress. Now consider this, Player launches the game and sign in to cloud service (play game services or whatever) and sign out by mistake or intentionally. Then make some good progress as a guest player and then later choses to sign in to loud again. Should I overwrite local progress (with more coins and scores) with cloud or do vice versa? I am confused. What should I do?

The solution I came up with to ask user if they want to overwrite the data or save the current local progress to cloud but this seems more ui work and user might find it less like a game and more like a boring software.(no offence to them).

Thanks.

# Answer
> 1 votes
As you’ve noted, you’ve got two ways to handle conflicting data. Either pick one, or try to merge the two games together. I have worked on games that have done both, and I highly recommend the first option.

With the first option, whenever there is a conflict, the game simply presents the options to the user, with a bit of info about each save state (eg. What level they are, how much time they’ve played, how much progress they’ve made, how many coins they have, etc.), allowing the user to pick which one with a simple button. It isn’t really that much UI work, and it gives the user agency over the choice, which they will almost always prefer. Trying to determine which game to keep automatically may either anger or confuse the user of they see their data change or become lost for reasons which are unknown to them.

The second option, where you try to merge the games together, works only in certain kinds of games, and is very game-specific, so I can’t really tell you the specifics of how it ought to be implemented. I can only say that it is a headache and a half, more error prone, and I much prefer the first option. Although if your game is simple enough, it could be the right solution for you.

---
Tags: savegame, google-play
---


# Question
Title: IConvertGameObjectToEntity interface on Unity ECS
Was working on ECS and following the tutorials by Mike Geig in Unite Copenhagen on YouTube(https://youtu.be/BNMrevfB6Q0), and understood that unity automatically converts transforms, mesh renderers and things like that to ECS, the IConvertGameObjectToEntity interface converts entities that I want specifically for my game. But, while following his tutorial exactly as he did it, the entities that I have on my game do not have colliders in them, but is seen in his demo, how do I resolve that?

EDIT: I've Instantiated an entity, and it works fine, but then implementing the `void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem);` from the `IConvertGameObjectToEntity interface`, I just have an entity, and only the mesh is visible, and an empty Component data that I've assigned on the Convert() method is available, I don't have a collider as it is on the prefab.

Here is my Spawn Entity Code:

```
void Start (){
        manager = World.Active.EntityManager;
        ObjectEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(ObjectPrefab, World.Active);

        for (int i = 0; i < 100; i++)
            SpawnTheObject();

```

}

```
private void SpawnTheObject()
{
    Entity object = manager.Instantiate(ObjectEntityPrefab);

    manager.SetComponentData(object, new Translation { Value = transform.position });
    manager.SetComponentData(object, new Rotation { Value = Quaternion.identity });

}

```

Here is The code attached to The Object:

```
public class AsteroidLifeECS : MonoBehaviour, IConvertGameObjectToEntity {
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
    MoveSpeed moveSpeed = new MoveSpeed { Value = MovementSpeed }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, moveSpeed);

    RotateSpeed rotateSpeed = new RotateSpeed { Value = RotationSpeed }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, rotateSpeed);

    Health health = new Health { Value = Health }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, health);
}

```

}

# Answer
> 1 votes
There is capsule collider attached to the bullet in the tutorial, But **Mike Geig** did not explain any thing about physics and collider, But as much i know unity "MonoBehavior" physics is not working with DOTS Entities.

So you have to install either "Havok Physics" or "Unity Physics".

More about Physics you can watch tutorials:

1. Leveraging DOTS-powered physics - Unity at GDC 2019.
2. NEW PHYSICS IN UNITY 2019! Beginner Friendly Overview.
3. Overview of physics in DOTS - Unite Copenhagen.

**Note:** I have not tested any of the package. So i could not tell how to get started with it, But there will be information in videos links I've shared.

I hope this will help, Sorry As I am not experienced with any of the package so I am not as much help full as I wanted to, Sorry.

Good Luck.

---
Tags: unity, entity-component-system, unity-dots
---


# Question
Title: How to receive a Knock Back when the player touched the enemy
I'm still new to C#, making my 2D game atm and my problem is how can I give my player a Knock Back when it touches the enemy. How to add it with this code?

```
public int health;

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Enemy"))
    {
        health -= 20;
        //Check for death
        if (health <= 0)
        {
            gameObject.SetActive(false);
        }
    }
}

```

# Answer
> 1 votes
I share some code which will help you out:

```
 public float force = 5;
 public ForceMode forceMode = ForceMode.Impulse;

 private void OnCollisionEnter2D(Collision2D collision)
 {
    if (collision.gameObject.CompareTag("Enemy"))
    {
        Debug.Log("Collision");
        health -= 20;
        //Check for death
        if (health <= 0)
        {
            gameObject.SetActive(false);
        }
        else
        {
            // Calculate Angle Between the collision point and the player
            ContactPoint2D contactPoint = collision.GetContact(0);
            Vector2 playerPosition = transform.position;
            Vector2 dir = contactPoint.point - playerPosition;

            // We then get the opposite (-Vector3) and normalize it
            dir = -dir.normalized;

            GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
            GetComponent<Rigidbody2D>().inertia = 0;

            //---------------------------------------------------------------------------------------------------------//
            //If the problme is not resolved then lock controle key. "playerControles" is a public static boolean which you have declare in the player controller script with true. then in this script you have to enable it or disable it.like
            playerControlerScript.playerControles = false; //if its true player input buttons will work and vice versa.
            Invoke("EnablePlayerControles", 0.5f); //if then amount of time is long then reduce it to the value you want.

            //Also in your player controller script wrap the inputs inside if condition like this if(playerControles){//input/inputs code}.
            //---------------------------------------------------------------------------------------------------------//

            // And finally we add force in the direction of dir and multiply it by force.
            // This will push back the player
            GetComponent<Rigidbody2D>().AddForce(dir * force, forceMode);
        }
    }
}

private void EnablePlayerControles()
{
   playerControlerScript.playerControles = true;
}

```

> Play with force amount and force mode to achieve the effect you want.

I hope this will help.

---
Tags: unity, c#, 2d, physics, platformer
---


# Question
Title: How to avoid a boring late game in strategy games while still keeping victories satisfying?
A common thing I've noticed in strategy games (of all types, 4X, RTS, MOBA, etc.) is that most games eventually get to a point where it is fairly clear who is going to win, and the rest of the game just becomes playing out the motions, and if the winning player/team doesn't make a major misstep, they will win.

This is just kind of the nature of strategy games. They inherently have a "snowball" effect. The gameplay is all about setting yourself up for success over your opponents in the future, and whoever does this better in the earlier stages of the game should win in the later stages. This happens in every strategy game to some extent, even the most classic. In Chess, it becomes increasingly harder to win if your opponent takes more and more of your pieces and forces your remaining pieces into tough situations.

As I said, this is just a fundamental part of the genre, so I'd hesitate to call it a problem. However, on occasion, in these types of games, you have matches where no player/team gains a significant advantage early, and the game comes down to the last turn. In my opinion, these are the most exciting and interesting matches you can have. Furthermore, when this doesn't happen, the late stages of the game can feel very boring for everyone involved, where the winning player is just awaiting their inevitable victory, and the losing player their inevitable demise (this can be especially unfun for the losing player, as they probably have very few options, and it is just really unlikely that they are having a good time).

So it would be cool if we could design a strategy game that avoids consistently falling into this state, right? Well, I have seen a handful of games like this, where a losing player consistently has avenues to victory, no matter how far behind they are. The issue with this is that if an upset happens (say one player was dominating the whole game, and then a losing player makes one good play at the end of the game to win), that victory can feel very unsatisfying for the winning player, as they may feel they didn't deserve it. Similar, the player who was winning most of the game may be very unhappy, as they may feel like victory was robbed from them, and they didn't deserve to lose. So essentially, no one is happy with the result. This approach may also make the early game less fun, as players may feel like it just doesn't matter.

So is it possible to design a strategy game that avoids both of these issues? A game where we don't consistently fall into a boring lategame with a forgone conclusion, and yet also keep victories feeling satisfying and deserved? Or are these issues far too fundamental to strategy gameplay to overcome?

If this question is too vague on its own, then we can focus on 4X strategy games, as those are the games I have experience with, and that I am interested in designing.

# Answer
**Make an additional win state that would end the game after it's rather obvious who the winner is.**

It might be best to make the victory condition optional in the game menu before starting the game.

E.g. for a turn based 4x game: If one player controls 80% of the map's territory game is over and the other players lost. If I remember correctly this is being done by several turn based strategy games I've played.

Another possibly unique example is the Close Combat series. The game ends when the enemy morale drops too low, thus preventing long and tedious "search and destroy" of every single enemy unit that would anyway end up surrendering if engaged due to an already broken morale.

A victory by "crushed morale" can be both "satisfying" (as per your question) to the player and avoid tedious gameplay at the same time.

Another option would be to simply enable overpowering the other player at any moment - e.g. one player sends his superior fleet of starships to the other player's home-world and destroys it due to the other player not being able to defend it thus resulting in game over. As simple as it gets.

There is also a possibility to give an incentive for other player to surrender - e.g. retreating from battle gives the other player an option of reusing the units in another battle.
> 4 votes

---
Tags: game-design, strategy
---


# Question
Title: Unity Screen.height / Screen.dpi is *not* equal to the screens height in real life
On mobile, I was planning on using Screen.dpi to work out the physical size of the screen and size controls accordingly.

But this quick test on my Galaxy S5 proves that the numbers from Unity are wrong.

1080 / 480 = 2.25 But the screen in real life is over 2.5 inches high.. So this is way off.

Any suggestions..? Right now I think I'll just leave this, and have the controls the same size in world space.. rather than risk making them worse.

# Answer
See **here** and **here**.

The gist is that on Android devices specifically, the values returned from Screen.dpi are often off because Android doesn't have the same info available (or in the presumed format) for Unity to crunch. So Unity forces the function Screen.dpi to call densityDpi instead. This method returns constant DPI densities provided by the manufacturer. They may be off by a little or a lot.

That second forum post link is provided by a Unity developer (back in 2013) and they offer a potential workaround function you can use instead of Screen.dpi (though it is not guaranteed). They also list phones where there WERE issues and phones were there were NOT issues. Unfortunately, it being 7 years later now, you will be swinging in the dark a little.

All this being said, the DPI of your phone should be publicly available via a simple Google search. When you find it, just multiply the density by the screen width to get the number of pixels horizontally, and multiply the density by the screen height to get the number of pixels vertically. The manufacturer will likely have more accurate screen size calculations than you can do with a ruler on their website.

**This** is an official developer guide on the Android website. Check out the content under "Device Compatibility", which includes multiple articles on screen sizes.
> 3 votes

---
Tags: unity, mobile, screen
---


# Question
Title: What is the difference between cudaExternalMemoryHandleTypeD3D12Resource and cudaExternalMemoryHandleTypeD3D12Heap?
When we import a D3D12 memory object into cuda we do something like this:

```
cudaExternalMemoryHandleDesc cuExtmemHandleDesc{};
cuExtmemHandleDesc.type = cudaExternalMemoryHandleTypeD3D12Resource; //here
//...
CheckCudaErrors(cudaImportExternalMemory(&m_externalMemory, &cuExtmemHandleDesc));

```

What is the difference between `cudaExternalMemoryHandleTypeD3D12Resource` and `cudaExternalMemoryHandleTypeD3D12Heap`? When should I use one or the other when importing memory object?

# Answer
`cudeExternalMemoryHandleTypeD3D12Heap` refers to a D3D12 heap object, whereas `cudeExternalMemoryHandleTypeD3D12Resource` refers to a D3D12 resource object. You'd choose the value that correctly represents the D3D12 object type you're referencing via `cudaImportExternalMemory`.

An `ID2D12Heap` is a representation of a contiguous allocation of memory, whereas an `ID3D12Resource` is somewhat higher-level, providing methods for (per the docs)

> organizing and manipulating simple arrays of data as well as multidimensional data optimized for shader sampling
> 1 votes

---
Tags: resource-management, directx12, cuda
---


# Question
Title: How can I create good looking football field lines?
I am trying to create a football field in a countryside with correct measurements of the lines. It's for my first person game. I have a terrain with mountains, trees, etc. and a flat surface for the field. What would be the best way to achieve good quality field like this?

I thought of these solutions:

* **paint the terrain** \- doesn't do the job, as the texture would need to be of resolution like 32k to make the lines not blured, seen from a first person view. It would also be inacurate painting it by hand.
* **create a textured plane and place it on top of the terrain with alpha mask** \- using raster graphics still would require massive resolution, but vector graphics might make sense here. It might be quite unhandy though and from a further distance might render badly.
* **project a vector graphics onto the terrain** \- this is probably the best of my ideas.

What would be the best approach and how to actually perform it?

# Answer
> 1 votes
There's a cool way to render crisp lines and contours using small resolution textures!

I usually see it being called *Signed Distance Field Text Rendering* \- it's what TextMeshPro uses - but there's nothing stopping the technique from being used for other purposes.

The general idea is that you pre-process the texture in a special way so that each pixel stores the distance to the closest edge (0.5 for pixels right on the edge, with the value going to 0.0 outside the shape and 1.0 inside). This ends up looking a bit like a blurry version of the original texture.

But when you render that texture using a special shader (which I belive in its simplest form only needs to do something like `output.a = texture.a >= 0.5 ? 1.0 : 0.0`) it becomes capable of being enlarged a lot without looking blurry.

Compare the second column with the fourth column in this image:

I've never implemented it before, only heard about it. Check these resources to get you started if you like the idea:

# Answer
> 0 votes
Unity Terrains are great. They allow the engine to make a lot of performance optimizations, both when it comes to rendering and when it comes to collision detection. So I would recommend you to paint your football field onto the terrain instead of representing it with one or more plane objects. But instead of creating one texture which represents the whole field, create many small textures which you can use as tiles.

* Create (or find) a small, tiling grass texture with which you paint the whole field.
* Open that texture with your favorite graphic editor and use it to create two variations of that texture: "grass with vertical line" and "grass with horizontal line". Use those textures to paint the horizontal and vertical lines of your football field.

(No, please don't create one by rotating the other by 90° - the grass won't tile anymore and the seams will look weird. Reload the original texture and draw another white line on it)
* Create textures with corners, t-sections etc. as you require them and use them to paint those points where horizontal and vertical lines intersect.
* Depending on whether your preferred kind of Football is Soccer or Handegg, you will also need to create some textures with arcs or textures with numbers.

Oh, and you should not worry too much about the measures being *exactly* as written in the rulebook. A rough approximation of the measurements and proportions will be good enough. As long as your game doesn't include any accurate measuring tools, nobody will notice if you are a bit off. And as long as you are not making an actual football game, nobody will care either.

---
Tags: unity, textures
---


# Question
Title: Unity Tile pallete isn't appearing in window tab
I'm trying to add a **tile pallette** to my scene in Unity. But when I go to

Window - 2D there is no tile pallette option

I'm using

v2019.2.11f1 (Personal)

# Answer
> 1 votes
For Unity version 2019 and up

1. Go to Window
2. Find package manager.
3. Look for 2D Tilemap Editor. (Wait for a few seconds to load all the packages)

Install it and you're good to go.

---
Tags: unity
---


title: Unable to edit tile sizes in unity

text:
# Question
Title: Unable to edit tile sizes in unity
I'm trying to change the size of sprites in unity to fit the palette. Except there are no options to change multiple sprite sizes at once.

But when I watched a youtube video on tilemaps and palettes, there were options to change the size of the entire palette!

v2019.2.11f1 (Personal)

# Answer
> 1 votes
It appears like you are looking at the inspector of one of several subsprites of an image asset you imported with the "Sprite Mode: Multiple" setting and then sliced with the sprite editor.

The second screenshot, however, appears to have marked several actual tile images, not the subsprites created from them. It appears like they are using a separate image file for each tile, and not one tileset image sliced into subsprites like you do.

Select the "tileset-sliced" image asset and you should see all the import options, including the sprite editor which allows you to reslice the tileset and the "Pixels per Unit" setting which applies to all the subsprites and affects their scaling in the game.

---
Tags: unity, tilemap, palette
---


title: How do I model a real-world building?

text:
# Question
Title: How do I model a real-world building?
This isn't exactly a game development question, but I am planning on using Unity as my engine and modeling in Maya so I was hoping folks on here might have some experience with this.

I want your advice or examples of modeling real-world buildings (inside and outside) ensuring accuracy but not necessarily detail.

The breakdown:

* I am doing a project in which I want to make a 3d interactive, explorable map of my university's campus.
* I am starting small with making one single building as my prototype.
* My plan is/was to model the building in Maya then import it into Unity to make the application.
* So far I have been able to access floor plans, however they lack measurements/dimensions (width, length, height, etc)
* I am in the process of attempting to get more resources but am unsure of what I will be able to acquire
* I have access to the building in question
* As a legitimate school project, I can try to get permission for various related needs

I wanted to know if anyone has any experience related to what I am doing or if anyone may be able to point me in a good direction for any resources that may help me.

# Answer
> 12 votes
In doing a similar project, I found the SketchUp modeling program to be excellent for copying existing architecture. That's what Google originally meant it for after all.

Here's an account of how I did this:

# Outsides

SketchUp's Photo Match feature (tutorial video) is an absolute killer.

It lets you to do this:

1. Load in a photograph of the real building from any perspective.
2. Adjust the model axes to match the photograph.
3. Edit the model directly over the photograph.

SketchUp automatically maps the photograph's textures to your model. You can take multiple photographs of the building from multiple directions and repeat this process for all of them.

This should also give you a pretty good idea of where the floor of each level of the building should be placed.

# Insides

Building insides are hard, but become easier once you have the outside frame. You can use SketchUp's Section Plane feature (tutorial page) to see inside your model. I recommend creating a floor polygon for each level of the building at a height based on the external model of the building. You can then Photo Match the floor plans as textures onto each of these floor polygons in turn!

You can then use the floor plan texture to draw in the contours of the walls and extrude them out to form actual walls. Depending on the level of detail you want, you can use the floor plan to correctly place doors and furniture. Once you're satisfied, just delete the floor plan texture from the floor.

# Answer
> 0 votes
Just found a recent good article on Getting Real-World Objects into Unity 3D that adds a different and good prespective using MeshRoom and MeshMixer.

The following image shows the three steps required to achieve it

> 1. Take several photos, as many as possible, around the object and use MeshRoom to digitize it. This tutorial illustrates the process. Upon saving Meshroom's own files the program also creates a folder named "MeshroomCache" (\MeshroomCache\Texturing) where it deposits the result in the widely exportable .obj format.
> 2. The digitized object will probably need some cleaning (parasite shapes of the surroundings) and/or reshaping. That's easily done with MeshMixer. Since digitized objects tend to be highly detailed and heavy on rendering, we may need to reduce/simplify the complexity/detail of the model, a feature included in MeshMixer. this program also exports to .obj format (among others). Look at Meshmixer Quick Tips tutorials.
> 3. Finally drag the .obj with the associated textures into a Unity 3D project. It's a straight standard process explained in Unity's manual.

All credits go to the Bael X3D's user vcard.

One other solution for the problem is to use apps like

to create the model and then import it as a normal 3D import.

---
Tags: unity, models, maps, maya
---


# Question
Title: How can I write a D3D12 texture in cuda?
One point about such pipeline is that everything happens in GPU and bypass the CPU.

The texture is created as such:

```
ThrowIfFailed(m_device->CreateCommittedResource(&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_SHARED,
            &texDesc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, nullptr, IID_PPV_ARGS(&TextureArray)));
// texture pixel format: DXGI_FORMAT_R32G32B32A32_FLOAT

```

How can I access in read+write to `TextureArray` (`ComPtr<ID3D12Resource> TextureArray;`) in cuda ?

# Answer
When creating the resources, one can export and map the texture resource to a cuda surface, subsequently available for direct read and write. The export and map needs only to happen once. The key steps are the following:

```
HANDLE sharedHandle{};
WindowsSecurityAttributes secAttr{};
ThrowIfFailed(m_device->CreateSharedHandle(TextureArray.Get(), &secAttr, GENERIC_ALL, 0, &sharedHandle));
const auto texAllocInfo = m_device->GetResourceAllocationInfo(m_nodeMask, 1, &texDesc);

cudaExternalMemoryHandleDesc cuExtmemHandleDesc{};
cuExtmemHandleDesc.type = cudaExternalMemoryHandleTypeD3D12Heap;
cuExtmemHandleDesc.handle.win32.handle = sharedHandle;
cuExtmemHandleDesc.size = texAllocInfo.SizeInBytes;
cuExtmemHandleDesc.flags = cudaExternalMemoryDedicated;
CheckCudaErrors(cudaImportExternalMemory(&m_externalMemory, &cuExtmemHandleDesc));

cudaExternalMemoryMipmappedArrayDesc cuExtmemMipDesc{};
cuExtmemMipDesc.extent = make_cudaExtent(texDesc.Width, texDesc.Height, 0);
cuExtmemMipDesc.formatDesc = cudaCreateChannelDesc<float4>();
cuExtmemMipDesc.numLevels = 1;
cuExtmemMipDesc.flags = cudaArraySurfaceLoadStore;

cudaMipmappedArray_t cuMipArray{};
CheckCudaErrors(cudaExternalMemoryGetMappedMipmappedArray(&cuMipArray, m_externalMemory, &cuExtmemMipDesc));

cudaArray_t cuArray{};
CheckCudaErrors(cudaGetMipmappedArrayLevel(&cuArray, cuMipArray, 0));

cudaResourceDesc cuResDesc{};
cuResDesc.resType = cudaResourceTypeArray;
cuResDesc.res.array.array = cuArray;
checkCudaErrors(cudaCreateSurfaceObject(&cuSurface, &cuResDesc));
// where: cudaSurfaceObject_t cuSurface{};

```

The cuda kernel can then be launched to write the texture. A semaphore also need to be created and shared:

```
ThrowIfFailed(m_device->CreateFence(m_fenceValues[m_frameIndex], D3D12_FENCE_FLAG_SHARED, IID_PPV_ARGS(&m_fence)));
NAME_D3D12_OBJECT(m_fence);

cudaExternalSemaphoreHandleDesc externalSemaphoreHandleDesc{};
memset(&externalSemaphoreHandleDesc, 0, sizeof(externalSemaphoreHandleDesc));
WindowsSecurityAttributes windowsSecurityAttributes;
LPCWSTR name{};
HANDLE sharedHandle{};
externalSemaphoreHandleDesc.type = cudaExternalSemaphoreHandleTypeD3D12Fence;
m_device->CreateSharedHandle(m_fence.Get(), &windowsSecurityAttributes, GENERIC_ALL, name, &sharedHandle);
externalSemaphoreHandleDesc.handle.win32.handle = sharedHandle;
externalSemaphoreHandleDesc.flags = 0;
CheckCudaErrors(cudaImportExternalSemaphore(&m_externalSemaphore, &externalSemaphoreHandleDesc));
m_fenceValues[m_frameIndex]++;

m_fenceEvent = CreateEvent(nullptr, false, false, nullptr);
if (m_fenceEvent == nullptr)
    ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError()));
WaitForGpu();

```

A full demonstration of it is available at https://github.com/mprevot/CudaD3D12Update
> 2 votes

---
Tags: directx12, cuda
---


# Question
Title: Making text scroll correctly with a textbox
So let me just get this right out of the way, I'm using SDL1.2 (Lispbuilder-sdl specifically, as I'm using Common Lisp), so on to the problem. I'm trying to make a scrollbar that can scroll text in an text-area, I already searched for an answer on this (google, here, etc) and I found this:

And since a picture says more than a thousand words, here's a screenshot of the issue (The scrollbox is 30 pixels in height):

So what I essentially want, is for the last line to be drawn when the box has gone all the way down, rather than continue scrolling after.

So a few notes before the code:

text-scrolling is only doing vertical scrolling as I want to solve this before making it work horizontally as well, the scrolling portion of the code (that handles moving of the scroll-box) supports both.

Hitboxes are used for the collision checking, something I'll rewrite at a later time, but essentially it's a rectangle with an absolute position that is used by collision-checking for the mouse (in this case, outside of this it holds more parameters than just position).

I use aux (local variable) for objects (such as the scroll box within scroll-bar), let (also local variable) is used in all other cases (especially if logic is involved).

```
;;Text-area scrolling:

(defun get-max-box-pos (scroll-bar)
  (- (h scroll-bar) (h (get-scroll-box scroll-bar))))

(defun text-field-shown-lines (text-field)
  (floor (/ (h text-field) (sdl:get-font-size " " :size :h :font (get-text-font text-field)))))

(defun line-pixels (text-field)
  (* (- (get-line-amount text-field) (text-field-shown-lines text-field)) (sdl:get-font-size " " :size :h :font (get-text-font text-field))))

(defun get-movement-rate (text-field scroll-bar)
  (let* ((max-box-pos (get-max-box-pos scroll-bar)))
    (- (ceiling (/ (line-pixels text-field) (if (= max-box-pos 0) 1 max-box-pos))))))

(defun text-scrolling (text-field scroll-bar texts &key (color (shf:get-color black))
                             &aux (scroll-box (get-scroll-box scroll-bar)))
  (scrolling scroll-bar)
  (setf (get-text-y text-field) (* (get-movement-rate text-field scroll-bar) (y scroll-box))))

```

So the thing I can't figure out\need help with, is how to calculate how much to move with, to ensure all the text can be scrolled (irregardless of the size of the scroll box), and not be too far apart.

Answer in the link provided (and my solution done before I checked that) causes it to move beyond.

Most of relevant\needed code (outside of drawing, instances, loops, etc):

```
;; Classes:
(defclass pos ()
  ((x :initarg :x :accessor x)
   (y :initarg :y :accessor y))
  (:documentation "Positions of an object, used as a super class for circle and rect"))

(defclass rect (pos)
  ((w :initarg :w :accessor w)
   (h :initarg :h :accessor h))
  (:documentation "A rectangle"))

(defclass text-field (rect)
  ((surface :accessor get-surface
        :initarg :surface)
   (text :accessor get-text
          :initarg :text
          :documentation "text to be used on the text-field")
   (text-x :accessor get-text-x
       :initarg :text-x)
   (text-y :accessor get-text-y
       :initarg :text-y)
   (state :accessor get-text-field-state
      :initarg :state)
   (color :accessor get-box-color
      :initarg :color)
   (alpha :accessor get-alpha
      :initarg :alpha)
   (font :accessor get-text-font
     :initarg :font
     :Documentation "Font used by the textfield")
   (background :accessor text-field-background
           :initarg :background)
   (amount-of-lines :accessor get-line-amount
            :Documentation "The amount of lines the text-field hold"
            :initarg :line-amount)))

(defclass scroll-box (rect)
  ((surface :accessor get-surface
        :initarg :surface)
   (color :accessor get-box-color
      :initarg :color)
   (direction :accessor get-box-dir
          :initarg :dir
          :documentation "what cordinate to scroll")
   (hitbox :accessor get-hitbox
       :initarg :hitbox)
   (active :accessor is-active-box?
       :initform nil
       :documentation "if the mouse is currently engaged in this box")))

(defclass scroll-bar (rect)
  ((surface :accessor get-surface
        :initarg :surface)
   (show :accessor show-scroll-bar?
     :initarg :show)
   (scroll-box :accessor get-scroll-box :initarg :scroll-box)
   (hitbox :accessor get-hitbox :initarg :hitbox)
   (bar-color :accessor get-bar-color :initarg :bar-color)
   (box-color :accessor get-box-color :initarg :box-color)))

;; The scrolling code:

(defun scroll-box-active-mouse? (scroll-box )
  "Changes the active state of the scroll-box if mouse is clicked on it"
  (and (shf:mouse-collision-check (get-hitbox scroll-box)) (sdl:mouse-left-p)
       (setf (is-active-box? scroll-box) t)))

(defun out-of-bounds? (box-pos box-size bar-size)
  "Checks if the scroll box is out of bound of the bar"
  (cond ((<= box-pos 0)
     'start)
    ((>= (+ box-size box-pos) bar-size)
     'end)))

(defun get-new-scroll-box-pos (mouse-pos bar-pos bar-size box-pos  box-size)
  "Returns the new position of the scroll box and it's hitbox in relative to the mouse position"
  (let ((bounds (out-of-bounds? box-pos box-size bar-size)))
    (cond ((and (string-equal bounds 'start) (< mouse-pos (+ bar-pos (round (/ box-size 2)))))
       (values 0 bar-pos))
      ((and (string-equal bounds 'end) (> mouse-pos (- (+ bar-size bar-pos) (round (/ box-size 2)))))
       (values (- bar-size box-size)
           (+ bar-pos box-pos)))
      (t (values (- (- mouse-pos bar-pos) (round (/ box-size 2)))
             (- mouse-pos (round (/ box-size 2))))))))

(defun scrolling (scroll-bar &aux (scroll-box (get-scroll-box scroll-bar))
                   (hitbox (get-hitbox scroll-box)))
  "Call to automatically check for, and cause scrolling.
Destructivly change the positions of scroll-bar, scroll-box(and it's hitbox)"
  (scroll-box-active-mouse? scroll-box)
  (when (is-active-box? scroll-box)
    (cond ((string-equal (get-box-dir scroll-box) :y)
       (setf (values (y scroll-box) (y hitbox))
         (get-new-scroll-box-pos (sdl:mouse-y) (y scroll-bar)  (h scroll-bar)
                     (y scroll-box) (h scroll-box))))

      ((string-equal (get-box-dir scroll-box) :x)
       (setf (values (x scroll-box) (x hitbox))
         (get-new-scroll-box-pos (sdl:mouse-x) (y scroll-bar) (w scroll-bar)
                     (x scroll-box) (w scroll-box)))))))

```

**Edit:** To clarify the 30 pixel box, it's 30 pixels (abritrary size, point is to have a pre-defined size of it) as I want to be able to do scrolling with a box that's already of a specific size (such as say, a circular sprite used for the box\scrolling, rather than a gray box).

**Edit 2:** I'm still not able to figure it out, anyway here's a pastebin snippet of the code to be able to run by itself(so any and all unrelated code removed, etc, only left in what is needed to get things up and running\working). Obviously need a Common Lisp enviornment with either quicklisp or ASDF to load up lispbuilder-sdl (ttf), and cl-utilities (read top comment of the snippet), personally using vera font, but obviously shouldn't matter since sdl gets the font height eitherway.

line 434 is where the scrolling of the box is done\start (anything before this point is drawing, classes, etc)

Line 472 is where the text-field scrolling is done, and where I am having problems

Line 478 is where the text is being moved

Line 504 is the main function (where you have to change the font path)

# Answer
> 1 votes
For anyone else stumbling on this in the future, the only solution I found is to stop the text from scrolling(leaving a empty-space for the scroll-box where moving it will have no effect anymore), which I think is what Daniel\_1985 alluded too in his comment.

The only way to circumvent the scroll-box empty-space issue(That I have found), is by having it resize based on amount of elements to scroll(however you decide to do and calculate scrolling).

So if someone do know, or manage to figure out how to do this without resizing the box, and not leaving any empty space for either elements in the field, or the scroll-box, I'd love to hear it!

---
Tags: sdl, text
---


# Question
Title: Updating RigidBody rotation and velocity only updates it's rotation
I'm currently making spaceship controller script. Control is simple, W/S to move forward/backward, A/D/ to rotate ship by Y Axis(yaw).

Spaceship is RigidBody node and has CollisionShape as children.

Here's the code for move forward/backward:

```
export var speed = 1
export var max_speed = 10
var current_speed = 0

export var key_acceleration = KEY_W
export var key_deceleration = KEY_S

func process_movement(delta):
    if Input.is_key_pressed(key_acceleration):
        current_speed -= speed * delta
    elif Input.is_key_pressed(key_deceleration):
        current_speed += speed * delta

    current_speed = clamp(current_speed, -max_speed, max_speed)

    linear_velocity = Vector3(0, 0, current_speed)

```

I need to limit it's maximum speed, so I updated velocity directly, not using something like add\_force.

Next is rotating code:

```
export var yawing_speed = 0.01
export var max_yawing_speed = 0.02
export var yaw_stop_threshold = 0.001
var current_yaw = 0

func process_yaw(delta):
    if Input.is_key_pressed(key_yaw_left):
        current_yaw += yawing_speed * delta
    elif Input.is_key_pressed(key_yaw_right):
        current_yaw += -yawing_speed * delta
    else:
        if current_yaw > 0:
            current_yaw -= yawing_speed * delta

            if current_yaw < yaw_stop_threshold:
                current_yaw = 0
        elif current_yaw < 0:
            current_yaw += yawing_speed * delta

            if current_yaw > yaw_stop_threshold:
                current_yaw = 0

    current_yaw = clamp(current_yaw, -max_yawing_speed, max_yawing_speed)
    rotation.y += current_yaw

```

In this code, I updated rotation.y directly. Each of this function works if run separately, however run these together, it only changed rotation, not velocity.

```
func _physics_process(delta):
    process_movement(delta)
    process_yaw(delta)

```

Change order of process\_movement and process\_yaw doesn't change anything. If I just run one of process\_movement and process\_yaw, it works perfectly.

Why my rigidbody ignored velocity and only rotated? Any advice will very appreciate it.

# Answer
Directly manipulating the velocity of a `RigidBody` in `_physics_process` is not supported. From the docs:

> The body’s linear velocity. Can be used sporadically, but **don’t set this every frame**, because physics may run in another thread and runs at a different granularity. Use \_integrate\_forces as your process loop for precise control of the body state.

You have 3 options to limit the max speed of your body:

# 1. Use a counter-force

Use `add_force` for acceleration, and apply a counter-force to slow it down. This counter-force should be proportional to the speed, such that when `speed == max_speed`, `force == counter_force` so the forces cancel out and the ship stops accelerating. This is similar to how air resistance works in real life (not that a spaceship would have "air resistance" per se).

I have an example of this from a game jam project I worked on recently (it is MIT-licensed, so feel free to borrow code).

# 2. Use a KinematicBody

With a `KinematicBody`, you have are able to precisely control velocity, but you don't get to participate in a full physics simulation. I also have an example of this from the same game, as I decided to switch my ship from a `RigidBody` to a `KinematicBody` to get more control over the movement.

# 3. Use \_integrate\_forces

You can keep using `RigidBody` but gain more precise control over its behavior by implementing custom logic in `_integrate_forces`. The docs discuss this briefly.
> 1 votes

---
Tags: physics, rigidbody, godot
---


# Question
Title: How to detect a collision and collision impact?
I would like to calculate "impact" of collision if its the right word for it. My scenario is: I have player, who is driving his vehicle. He then hits the wall while still in vehicle. I want to know if the collision happend and calculate the impact of collision, so later I know how much hp the player should lose depending how hard the hit was. I hope I made clear what I want to achieve.

What I'm currently doing is storing the previous vehicle speed and calculating the impact like this `(previousSpeed - currentSpeed) / frameTime`. It gives me some results but it's not consistent. Any other idea? It's in 3D so I have access to 3d vectors if it helps in any way.

# Answer
> 0 votes
I'll take impact as "any consequence".

You are talking about **momentum**. It is represented by a vector, its value is \\$MLT^{-1}\\$ dimensionned. It is related to mass and speed this way: \\$\vec p=m\vec v\\$ where \\$\vec p\\$ and \\$\vec v\\$ are vectors. Momentum is conserved in isolated systems (no external force applied), which is the key point to make your calculations; you'll need to add some mass (eg., divide your objects (player) into smaller regions, each having a mass). Momentum is related to force as such: \\$\vec ft=\vec p\\$ where \\$t\\$ is time, \\$\vec f\\$ force vector.

In order to make something realistic you'll also have to set rigid and soft body mechanics (with local mass), including elasticity, and material cohesion (if the momentum is high enough, the material can break or be teared).

A collision is detected as a sudden change of momentum (sudden change of speed).

A bit more here: https://en.wikipedia.org/wiki/Momentum

---
Tags: collision-detection, vehicle
---


title: Domain warping with Perlin noise

text:
# Question
Title: Domain warping with Perlin noise
I'm trying to achieve the effect from https://www.iquilezles.org/www/articles/warp/warp.htm

with no success. Here is the experiment http://jsfiddle.net/fro5y0jm/15/ with canvas. Any ideas?

# Answer
Looks like your domain warping amplitude is just too small.

Crank up your `q` to about 20x its current value and you'll get very pronounced domain warping:

I made this image by modifying your code to replact the `4.0*` with `80.0*`:

```
function pattern(x, y, scale, octaves, lacunarity, gain){
    var q = [
            fbm(x, y, scale, octaves, lacunarity, gain),
            fbm(x+5.2, y+1.3, scale, octaves, lacunarity, gain),
      ];

    return fbm(x+80.0*q[0], y+80.0*q[1], scale, octaves, lacunarity, gain);
}

```
> 2 votes

---
Tags: procedural-generation, perlin-noise, fractal
---


title: How to get DXGI_ERROR description?

text:
# Question
Title: How to get DXGI_ERROR description?
In a D3D12 program, I encounter a DGXI\_ERROR (`CreateSharedHandle` return an `int` `<0`), but I could not find a way to translate it into the "error description" or "error name" (or both).

I have a description by Microsoft: https://docs.microsoft.com/en-us/windows/win32/direct3ddxgi/dxgi-error

Is there such function out there ?

# Answer
> 0 votes
```
if (result < 0)
{
    LPWSTR errorText{};
    auto result2 = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr, result,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPWSTR>(&errorText), 0, nullptr);
    wstringstream o;
    auto justfile = JustFile(file);
    o << caller << "(): " << func << " at " << justfile.c_str() << ":" << line <<
        " [" << GetErrorDescr(result).c_str() << "][" << errorText << "]";
    LogMessage(L"%s\n", o.str().c_str());
    //throw exception();
}

```

and with:

```
inline string GetErrorDescr(int error)
{
    switch (error)
    {
        case DXGI_ERROR_INVALID_CALL:
            return string("DXGI_ERROR_INVALID_CALL: The method call is invalid. For example, a method's parameter may not be a valid pointer.");
        case DXGI_ERROR_WAS_STILL_DRAWING:
            return string("DXGI_ERROR_WAS_STILL_DRAWING: The previous blit operation that is transferring information to or from this surface is incomplete.");
        case E_FAIL:
            return string("E_FAIL: Attempted to create a device with the debug layer enabled and the layer is not installed.");
        case E_INVALIDARG:
            return string("E_INVALIDARG: An invalid parameter was passed to the returning function.");
        case E_OUTOFMEMORY:
            return string("E_OUTOFMEMORY: Direct3D could not allocate sufficient memory to complete the call.");
        case E_NOTIMPL:
            return string("E_NOTIMPL: The method call isn't implemented with the passed parameter combination.");
        case S_FALSE:
            return string("S_FALSE: Alternate success value, indicating a successful but nonstandard completion (the precise meaning depends on context).");
        case S_OK:
            return string("S_OK: No error occurred.");
        default:
            return string("Some other D3D11 error (file not found|too many unique state objects|too many unique view objects).");
    }
}

```

and:

```
inline string JustFile(const char* file)-> string
{
    auto f = string(file);
    replace(f.begin(), f.end(), '\\', '/');
    auto justfile = string(f.substr(f.find_last_of('/') + 1));
    return justfile;
}

```

If more details are required, enable the DGXI debug controller:

```
#if defined(_DEBUG)
    // Enable the debug layer (requires the Graphics Tools "optional feature").
    // NOTE: Enabling the debug layer after device creation will invalidate the active device.
    {
        ComPtr<ID3D12Debug> debugController;
        if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
        {
            debugController->EnableDebugLayer();
            dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
        }
    }
#endif

```

More here: https://walbourn.github.io/dxgi-debug-device/

---
Tags: directx, directx12, error-management
---


title: Unity ceiling light issues

text:
# Question
Title: Unity ceiling light issues
I'm trying to get back into Unity and I've been playing around with lighting. I modelled a simple lightbulb in Maya and have been trying to create a hanging ceiling light but I'm struggling to get it to work. No matter where I place the point light, it appears to originate from the ceiling and the bulb remains dark. Ideally, I would like the light to originate from inside the bulb and spread across most of the room, while also making the bulb glow. I'm sure this is a simple task but I would really appreciate any tips in the right direction. Thanks

# Answer
The Light component is used by the surrounding objects' shaders to compute how much illumination their surfaces should reflect.

But from the perspective of the lightbulb itself, that light isn't shining onto the surface at all - the surface is facing directly *away* from the light. So it correctly does not reflect any of it. Some shaders will try to simulate transmission through a material, but for a simple case like a light bulb that's only on or off, we can do something even easier.

When you want an object to self-illuminate from within, the way to achieve that is to give it a material with "Emission" enabled.

You can then give the emission an HDR colour & intensity value, and even add a mask to control which parts of the object glow.

If you want a halo around the light, that's a third technique yet - you can achieve it using a lens flare, or by using a bloom filter on your camera to make bright spots in your image bleed out into their surroundings a little, or with a camera-facing quad you stick on your lightbulb if you want to exactly control the look of the halo.
> 0 votes

---
Tags: unity, lighting
---


# Question
Title: After rotated by Z-axis, X/Y axis still rotating just like z is 0
I'm making aerial vehicle controller, which can rotate 3 axis: X(Pitch), Y(Yaw), Z(Roll).

Rotating x(pitch) and y(yaw) axis works fine, however after I rotated z(Roll) axis, x/y rotation gave me weird result, it seems like it still rotating just like z axis didn't rotated(0).

First I thought that it was some kind of gimbal lock problem, but it wasn't, it still happens using quaternion.

Here's the video I demonstrate: https://www.youtube.com/watch?v=8cdBSxcmiWE&feature=youtu.be

Note that I tried all these and had same results:

```
# Using Euler
rotation.x += pitch

# Using Euler II
rotate_x(pitch)

# Using Quaternion
var qRot = Quat(transform.basis)
var r_euler = qRot.get_euler()
var new_rot = Vector3(r_euler.x + pitch, r_euler.y, r_euler.z)
qRot.set_euler(new_rot)
var new_basis = Basis(qRot)
var new_transform = Transform(new_basis.x.normalized(), new_basis.y.normalized(), new_basis.z.normalized(), transform.origin)
set_transform(new_transform)

```

Is there a something that I missed? Any advice will very appreciate it.

# Answer
> 1 votes
When rotating your object, make sure you apply rotations around the local axes, not the global ones. Even in your third case, it does look like you are encountering gimbal lock. Here's a demo:

```
extends Spatial

func _ready():
    $Ship1.angular_velocity = Vector3(1, 0, 0)
    $Ship2.angular_velocity = Vector3(1, 0, 0)
    yield(get_tree().create_timer(1.0), "timeout")

    $Ship1.angular_velocity = Vector3(0, 1, 0)
    $Ship2.angular_velocity = $Ship2.global_transform.basis.y.normalized()
    yield(get_tree().create_timer(1.0), "timeout")

    $Ship1.angular_velocity = Vector3(0, 0, 1)
    $Ship2.angular_velocity = $Ship2.global_transform.basis.z.normalized()
    yield(get_tree().create_timer(1.0), "timeout")

```

`Ship1` is the one further from the camera. It is ralways rotated about the global axes. Note that when we get to roll (z rotation), it is not rotating about the local Z axis (a vector extending out of the nose of the ship).

`Ship2` is rotated first around global X, then about *local* y (`basis.y`), then about *local* z (`basis.z`). When it gets to roll, it is rolling around the nose of the ship, which is likely the behavior the player expects.

---
Tags: matrix, transformation, godot, rotate
---


# Question
Title: Making unity inspector accept classes that inherit from a base class
I have a base class that has a lot of classes inheriting from it, I want to make a script that you can drop one of these derived classes into. How do i do that?

```
abstract class thingy : UnityEngine.ScriptableObject
{
    // methods, variables, etc
}

class awsomeThing : thingy
{
    // Imagine there are more of these classes with different names...
}

```

I've managed to get the thingy class to show up but (as you can guess) you can only drag in that script in there, is there a way to get the inspector to accept the multiple `awsomeThing` classes?

# Answer
> 2 votes
I'm unable to reproduce the problem described in this question when using types that are derived from `MonoBehaviour` or `ScriptableObject` as shown above.

Using the following code:

```
public abstract class SomeBaseClass : ScriptableObject
{
    public int baseClassInt = 5;
}

[CreateAssetMenu(fileName ="Derived.asset", menuName ="Testing/Some Derived Class")]
public class SomeDerivedClass : SomeBaseClass
{
    public string derivedClassString = "foo";
}

public class PolymorphicTest : MonoBehaviour
{
    public SomeBaseClass someBaseInstance;
}

```

An instance of type `SomeDerivedClass` is accepted just fine in an inspector field of type `SomeBaseClass`:

---
Tags: unity, c#, oop, inheritance
---