# Question
Title: How to scale an object in one direction without moving the opposite edge?
I am using Unity. In my game, I have an SpriteRenderer and I'd like it to increase its size

I'd like it to lengthen to the right, without moving the left edge.

I tried changing its scale to something bigger than its original scale and it changes into something like this, growing to both the left and the right:

I also tried to increase its position together with its scale but then it didn't work.

> **Editor's note:** this is where you tell us *how* it "didn't work". What *exactly* did you try, what results did you get, and how did those results differ from what you wanted?

My Object is configured like this in UnityEngine:

# Answer
> 2 votes
The pivot of your object is at it's center. So to keep the bottom left corner in the same position, you need to move the object up and to the right by:

(bigSize / 2.0) - (originalSize / 2.0)

Alternatively, just put a parent gameObject at the corner, and child your GameObject to it, and apply the scaling to the parent instead.

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


title: Custom cutscene system in Unity

text:
# Question
Title: Custom cutscene system in Unity
I'm trying to make a RPG game (without the typical leveling and such. Just a roleplaying game) based on Wasted Youth Part 1 (which is an old flash game where you take control of a teenage kid sent to a boarding school for troubled children who keep getting kicked out of schools).

Here's an example of a cutscene in Wasted Youth Part 1: https://i.stack.imgur.com/NeR26.jpg

I've decided to go about creating a custom cutscene system due to the fact I find the timeline too limited for what I want to do.

I've also already made the basics of a cutscene system (it's very hacked-together and more servers as a proof-of-concept) shown here: https://twitter.com/SkullAberration/status/1079132052761518082.

One idea(along with pros and cons) I've already come up with is to store the cutscene in a separate scene with hardcoded(right word?) movement/animations/etc. This seems good since it helps me store cutscenes in an easy way and easily be able to customize what happens in the scene. An issue, however, is persistence. If a cutscene happens in a school cafeteria(as one does in WYP1) how, when I load the player back into the main scene, do I easily make sure they're in a cafeteria filled with people still?

If anyone has any information/suggestions on how I could go about creating a cutscene system like I've described(hopefully good enough), that'd be great!

# Answer
> 0 votes
I've decided to go with the scene approach I mentioned, but with a few tweaks.

Rather than storing cutscenes in a separate scene, I will store entire missions + their associated cutscenes in a separate scene. This way I can keep persistence after cutscenes since I won't be changing scene afterwards and by the time the player has finished a mission, the world should be back to it's normal state/there would be nothing that should persist into gameplay.

Above all this, I'll have a 'world manager' that deals with the 'world' of the game. For example, if player has completed mission X then change NPC Y's dialogue to Z or if time of day is afternoon, put all NPCs inside the cafeteria eating.

# Answer
> 1 votes
First off, Unity has a good tutorial on persistence. If you're not big on scripting, should probably check out at least a couple of their Intro to Scripting tutorials first, just to get used to the basics. Or jump right in, and look things up if you get lost.

## Option 1: Save state, play cutscene, restore state

Decide what elements actually change in your cutscene: player location/orientation, moving NPCs ("cast"), items changing appearance or location ("props"), lighting conditions. Just before changing to the new scene, you store all that information. At the end of the cutscene, just before going back to normal-gameplay, you restore everything to its previous state that you saved.

## Option 2: Animate anything

Almost any scene or UI element can be animated using custom animation clips. You play out your cutscene, then in the last couple of frames, "fade to black" and reset everything that was animated. It's a little more advanced, but you can also add Animation Events to trigger any code you want, including dynamic positioning, dialogue, or player-input.

There was a really eye-opening Unity live session a few years back, Animate Anything with Mecanim, as well as some more recent Unite sessions & blog posts (Creative Scripting for Timeline) that are worth checking out for ideas on how to get the most out of the built-in tools.

## Option 3: There's an Asset for that

There are plenty of assets on the Unity Asset Store that already do this, if you're not specifically looking to write everything from scratch. My personal recommendation would be Adventure Creator, since it is well-documented & supported, is specifically designed for stats-light RPGs (what used to be called adventure games :), and it has a really good node-based visual-scripting system built-in, as well as scene-to-scene and save/load persistence.

I don't own it, but I do use it, and find it does everything I need it to and then some. It goes on sale periodically, but you can check out the fairly extensive demos/tutorials on the dev's Youtube channel (Chris Burton).

---
Tags: unity, cutscene
---


# Question
Title: Removing the contains ads label from the google play store
So previously in my Unity android game we had ads. Now I'm creating a demo version of the game from that project. I have succesfully removed all other permisions but the 'contains ads' still shows up on the google play store page. I have disabled the ads service from the services tab in the editor. I have comented or deleted all references to UnityEngine.Advertisements. Exporting the project to android studio results in this manifest :

```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.LeadersPlay.LeadStreet" xmlns:tools="http://schemas.android.com/tools" android:versionName="1.26" android:versionCode="45" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:isGame="true">
    <activity android:label="@string/app_name" android:screenOrientation="sensorLandscape" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false" android:name="com.LeadersPlay.LeadStreet.UnityPlayerActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
    <meta-data android:name="unity.build-id" android:value="21447188-7121-4c3e-8f0e-6602ae1caa74" />
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />
    <meta-data android:name="android.max_aspect" android:value="2.1" />
  </application>
  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>

```

Where I cant find a single reference to adverts. I have also waited for the new version to be refreshed in the store.

# Answer
In addition to remove the ads from you app it looks like to you need to update your ad settings in the Google Play Console.

This can be found (as of 2018) by selecting the App you want to modify and then selecting **Store presence -\> Pricing & distribution** and setting **Contains ads** to no.
> 4 votes

---
Tags: unity, android, unity-ads
---


# Question
Title: How to change object details based on zoom
I have created the map of a huge terrain (10,000 x 12,000) vertices, which results in about 240 million triangles. Loading all these is very heavy and slows down the scene significantly. To make it more efficient, I am thinking of using a fraction of the vertices when the camera is away (say one for every 10 vertices) and as the camera zooms in on the map, I would increase the number of vertices.

The problem is, even when the camera is zoomed in and a small fraction of the map is viewed at full resolution, the scene is still loading very slowly because of all the drawings that are happening outside the viewport.

My question is, how do I calculate which vertices are in the viewport so that I don't draw them. Or, alternatively, is there a better way of handling increasing the resolution as I zoom in (note that I am not using textures)

# Answer
120M vertices is indeed a large load to run through your vertex shader, even just for OpenGL to cull them.

I assume you already have the terrain defined as VBOs that are loaded at launch, and not every frame?

It's best to divide up your terrain mesh in chunks, and do some culling on the CPU, and only draw (partially) visible chunks.

This is a process that is referred to as Frustum Culling. And this video is an excellent illustration of how it works.

Note that you could start off with a very quick win by not drawing anything that is behind the camera. This should give you a factor 2 win, if the camera is at the center of the mesh.

Just test each chunk's direction: take dot product with camera-forward vector. If the dot product is negative, don't draw it. You may need a little margin built in so that you don't cull the ground directly underneath the camera though.

To do a full cull process, you need to solve the intersection between the camera frustum and the terrain chunk's AABB.
> 1 votes

---
Tags: opengl
---


title: Raycast does not go to target position

text:
# Question
Title: Raycast does not go to target position
There is a part in my script where I need to make a raycast check from my gun's muzzle to the enemy. This enemy could be anywhere around player.

I found my ray is not connecting to the target position!

```
public Transform target, Bullet_position;

void Update {

  if (target != null)
  {
      RaycastHit hit;
      if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500)
      {
          Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);

          if (hit.collider.tag == "enemy")
          {
              print(" In range and I can see you! ");
          }
          else
          {
              print(" None! ");
          }
       }
    }
} // end update.

```

# Answer
The second argument in both of these methods is the *direction* you want the ray to travel, not the *position* you want it to reach. So when written like this...

`if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500))`

`Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);`

...you're asking for a ray along the line from:
`Bullet_position.position`
to:
`Bullet_position.position + target.position`

If you prefer to specify two points, instead of a point and a direction, you can instead use the LineCast / DrawLine methods.
> 1 votes

---
Tags: unity, raycasting
---


# Question
Title: Shooting the closest enemy that you can see
I'm trying to make my main character aim at the closest enemy that he can see.

My issue is with the close range criterion taking priority. If the enemy is near the player but the player can't see him, I'd like the player to look for another enemy inside his range.

As you can see in the image, There is an enemy behind the wall. The player is not aiming at him because he can't see him. So far this is correct.

But the player is also ignoring the enemy in front of him because he's busy rejecting the one behind the wall.

What he should do is aim at the one in front of him, because he can see him and he is inside the player's range.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.UI;
public class clickme : MonoBehaviour
{

private NavMeshAgent mAgent;
public float mark, ToPoint;
public bool actives, seeEnemy;
private Transform target;
public float range, enemyDistance; // range is player eyes field.
public float speed = 5.0f;
public Transform aiming_point, playerEye;
private GameObject[] targets;

void Start()
{
    targets = GameObject.FindGameObjectsWithTag("enemy");
    target = targets[0].transform;
    seeEnemy = false;
}

void Update()
{

    if (mAgent.remainingDistance <= mAgent.stoppingDistance)
    {
        actives = false;
        if (actives == false && playerEye == true && target != null)
        {

            if (enemyDistance <= range)
            {
                Vector3 dir = target.position - transform.position;
                Quaternion lookRotation = Quaternion.LookRotation(dir);
                Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * speed).eulerAngles;
                transform.rotation = Quaternion.Euler(0f, rotation.y, 0.0f);
            }

        }
        else  {

        }

    }
    else   {
        actives = true;

    }

    updateTarget();

} // end update

void updateTarget()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
    float shortesDistance = Mathf.Infinity;
    GameObject nearestEnemy = null;
    foreach (GameObject enemy in enemies)
    {
        float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
        if (distanceToEnemy < shortesDistance)
        {
            shortesDistance = distanceToEnemy;
            nearestEnemy = enemy;

            RaycastHit hit; // can I see my closent enemy or not ?
            if (Physics.Linecast(playerEye.position, nearestEnemy.transform.position, out hit))
            {
                Debug.DrawLine(playerEye.position, nearestEnemy.transform.position, Color.blue, range);

                if (hit.collider.tag == "enemy")
                {
                    seeEnemy = true;
                    print(" I can see enemy !");

                }
                else
                {
                    seeEnemy = false;
                    print("No enemy here!");

                }
            }
        }

    } // end foreach

    if (nearestEnemy != null && shortesDistance <= range && seeEnemy == true)
    {
        target = nearestEnemy.transform;
        aiming_point = target.transform.Find("aim");
        enemyDistance = Vector3.Distance(transform.position, target.transform.position);
    }
    else
    {
        target = null;
        aiming_point = null;
        seeEnemy = false;
        enemyDistance = 0;
    }

} // end target

}

```

# Answer
There are a few problems here.

First, don't do this every frame in Update:

```
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");

```

The find methods are generally slow. It's OK to use for initialization, but if you just want a list of all enemies - which is likely to be very similar to the list from last frame - then store that list somewhere and update it when you add/kill an enemy.

Or, if you only care about enemies in your vision cone / range, then you should instead use a physics query to find them, like `Physics.OverlapSphere` or `OverlapBox` (or their `NonAlloc` versions for efficiency). You can put all the enemies on a specific physics layer, then filter the physics query to check only that layer, in a bound tightly fitted to your shooting range. This will minimize the number of objects you have to iterate over to just the ones that are potentially interesting.

Now, your main logic problem is just doing your visibility check and target update in the wrong order:

```
if (distanceToEnemy < shortestDistance)
{
    shortestDistance = distanceToEnemy;
    nearestEnemy = enemy;

    RaycastHit hit;
    if (Physics.Linecast(playerEye.position, nearestEnemy.transform.position, out hit))
    {...

```

This translates to:

1. Choose the nearest enemy.
2. Then, if you can see that enemy...

But what you *want* is:

1. Choose the nearest enemy *that you can see*.

ie. we don't want to consider candidate enemies who are nearby but not visible. So...

```
if (distanceToEnemy < shortestDistance)
{
    // DO NOT immediately set a new shortestDistance here,
    // because we don't yet know whether this is an enemy we can see.

    RaycastHit hit;
    if (Physics.Linecast(playerEye.position, enemy.transform.position, out hit))
    {
        if(hit.collider.CompareTag("enemy")
        {
            // NOW we know this is not just a nearby enemy,
            // but a nearby VISIBLE enemy, and thus worth tracking.
            shortestDistance = distanceToEnemy;
            nearestVisibleEnemy = enemy;
            ...

```
> 5 votes

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


# Question
Title: Instantiate unity sometimes lags the game some times it doesnt
I have a script that instantiates a object lets say every half a second. THis object is of the type .fbx and has a file size of 53kb, lets call this object `A`. When i use this object my script instantiates the objects without any freezes or any other problems.

Now i have an other object also of type .fbx and also with a filesize of 53kb lets call this object `B`. Now when i want to instatiate object my my game freezes a few frames upon instantiation.

Why? Is there a way to instatiate objects more efficiantly? I already looked at using object pooling but this doesnt really works in my case.

See here a screenshot for object `A`, and its components:

See here object `B` and its components:

Per request the code that does the instantiation of the objects:

```
public class ForLoopVisualization1 : MonoBehaviour {

    public DetectorAreaScript ElementDetector;
    public GameObject TowerElement;
    public Transform TowerElementsParent;
    public bool WigglyTower = false;
    public float ElementSpacing, Wiggeliness;

    private Collider BuildElementCollider;
    private Transform BuildElementTransform;
    private Vector3 TowerElementPos;
    private int TowerElementCount, CreatedElements;
    private bool StartBuildingTower = false;
    private float Delay = 0.5f, TowerElementSize;

    // Use this for initialization
    void Start () {
        ElementDetector.DetectedData += OnObjectEnterDetector;
        Destroy(TowerElement.GetComponent<Rigidbody>());
        TowerElementSize = TowerElement.GetComponent<Collider>().bounds.size.y;
        TowerElementPos = TowerElementsParent.position + new Vector3(0, TowerElementSize * 1.5f + ElementSpacing, 0);
    }

    // Update is called once per frame
    void Update () {
        if(StartBuildingTower && CreatedElements < TowerElementCount)
        {
            Delay -= Time.deltaTime;
            if(Delay <= 0)
            {
                CreatedElements++;
                var te = Instantiate(TowerElement, TowerElementPos, Quaternion.identity);
                te.transform.SetParent(TowerElementsParent);
                if(WigglyTower) TowerElementPos += new Vector3(Random.Range(-Wiggeliness, Wiggeliness), TowerElementSize + ElementSpacing, Random.Range(-Wiggeliness, Wiggeliness));
                else TowerElementPos += new Vector3(0, TowerElementSize + ElementSpacing, 0);
                Delay = 0.4f;
            }
        }
        else if(StartBuildingTower)
        {
            StartBuildingTower = false;
            // StartCoroutine(EjectVar()); // add when bugs are fixed..
        }
    }

    void OnObjectEnterDetector(System.Object sender, DetectedVariableData data)
    {
        if(data.DetectedObjectType == DetectedType.Variable)
        {
            var vals = ElementDetector.DetectedVariable.GetVariableValue();
            TowerElementCount = vals.IntValue;
            if(CreatedElements > 0)
            {
                foreach (Transform child in TowerElementsParent)
                {
                    Destroy(child.gameObject);
                }
                CreatedElements = 0;
            }
            TowerElementPos = TowerElementsParent.position + new Vector3(0, TowerElementSize * 1.5f + ElementSpacing, 0);
            StartBuildingTower = true;
        }
    }

    IEnumerator EjectVar()
    {
        yield return new WaitForSeconds(0.8f);
        ElementDetector.EjectDetectedElement(new Vector3(-1, 0, -1));
    }
}

```

If something is unclear let me know so i can clarify the post!

# Answer
> 1 votes
So after all great help from the comments i found out it actually had to do with the meshCollider on the object. The objects that caused the problems had a really smooth surface, which results in some rather long computing times to generate the convex mesh collider. Which resulted in the little bits of lag. So i just made a custom low poly collider for the problematic objects and that fix the issues.

Hope this helps anyone. If more information is needed i am happy to help!

---
Tags: unity, gameobject, instancing
---


# Question
Title: Why is this LIBGDX Action behavior THE EXACT OPPOSITE of what I expect?
Here is a code snippet of the relevant section in my render loop. My intention was to make the actor who was currently focused blinking, to indicate that it was the currently selected UI element. But after noticing that setting the condition of the if statement to == was giving me THE EXACT OPPOSITE of what I expected (namely: all elements that had previously had focus that were not the currently focused element of the stage were blinking), I changed it to the opposite and received the desired outcome.

QUESTION: What fundamental lesson of how Actions work am I missing? Why is this happening?

```
    Actor currentFocus = stage.getKeyboardFocus();

    if(currentFocus != gameVolumeSlider){
        gameVolumeSliderLabel.addAction(Actions.forever(Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
    }
    if(currentFocus != musicVolumeSlider){
        musicVolumeSliderLabel.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
    }
   if(currentFocus != backButton){
        backButton.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
    }

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

```

# Answer
@DMGregory was right: adding it over infinitely is NOT the correct way to handle this--so dealing with it in the render() method is NO-GO.

How I solved this is as follows. I checked for the position in the Input Handlers and then added/removed the blinking behavior in a procedural fashion:

```
 stage.setKeyboardFocus(gameVolumeSlider);

 gameVolumeSliderLabel.addAction(Actions.forever(Actions.sequence(fadeIn(.5f),fadeOut(.5f))));

 stage.addListener(new InputListener() {
        public boolean keyDown (InputEvent event, int keycode) {
            if (keycode == Keys.DOWN  || keycode == Keys.S) {
                if (buttonToggleState == 3) {
                    buttonToggleState = 1;
                } else {
                    buttonToggleState++;
                }
                System.out.println(buttonToggleState);

                if(buttonToggleState == 1){
                    gameVolumeSliderLabel.addAction(Actions.forever(Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    backButton.clearActions();
                    backButton.addAction(fadeIn(.5f));
                }
                if(buttonToggleState == 2){
                    musicVolumeSliderLabel.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    gameVolumeSliderLabel.clearActions();
                    gameVolumeSliderLabel.addAction(fadeIn(.5f));
                }
                if(buttonToggleState == 3){
                    backButton.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    musicVolumeSliderLabel.clearActions();
                    musicVolumeSliderLabel.addAction(fadeIn(.5f));
                }

            }

            if (keycode == Input.Keys.UP || keycode == Keys.W) {
                if (buttonToggleState == 1) {
                    buttonToggleState = 3;
                } else {
                    buttonToggleState--;
                }
                System.out.println(buttonToggleState);

                if(buttonToggleState == 1){
                    gameVolumeSliderLabel.addAction(Actions.forever(Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    musicVolumeSliderLabel.clearActions();
                    musicVolumeSliderLabel.addAction(fadeIn(.5f));
                }
                if(buttonToggleState == 2){
                    musicVolumeSliderLabel.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    backButton.clearActions();
                    backButton.addAction(fadeIn(.5f));
                }
                if(buttonToggleState == 3){
                    backButton.addAction(Actions.repeat(RepeatAction.FOREVER, Actions.sequence(fadeIn(.5f),fadeOut(.5f))));
                    gameVolumeSliderLabel.clearActions();
                    gameVolumeSliderLabel.addAction(fadeIn(.5f));
                }

            }

```

So in conclusion it was doing the exact opposite because this was unintended behavior. The render loop was calling the if that was evaluating to true over and over and over again and *I think* it was keeping that method call from animating because it was constantly stuck in a loop re-adding those instructions(?) That's my theory, either way... this is how you solve it and add the desired blinking behavior to Actors on a Table on a Stage with keyboard input in LIBGDX.scene2d.ui.
> 0 votes

---
Tags: java, libgdx, gui, scene2d, user-interface
---


# Question
Title: Is there a word that describes when too much audio is being play simultaneously?
In Unity, before I managed sounds properly, if too many accumulated at the same it would become this loud drowned out mega sound (like the speakers got blown out). With proper audio management this is never an issue, but it's funny how many times I see this problem come up in professional level games (notably Demon's Souls and Dark Souls when too many collisions happen with breakable boxes triggering too many sounds to happen at once).

Is there a word that describes that drowned out mega sound that happens when too many sounds are being played at once? Also, what's the process that's happening on the audio technical side when this sound is played, meaning are the sounds just being shoved into one mixer or something?

# Answer
> 1 votes
The word I believe you are searching for is cacophony.

ca·coph·o·ny

/kəˈkäfənē/

noun: cacophony; plural noun: cacophonies

a harsh, discordant mixture of sounds.

"a cacophony of deafening alarm bells"

synonyms: din, racket, noise, clamor, discord, dissonance, discordance, uproar "despite the cacophony, Rita slept on"

---
Tags: audio, sound, terminology, sound-effects
---


# Question
Title: Minecraft Modding - How do I use OpenGL stencil functions alongside the game's GlStateManager?
Note: I am using Minecraft Coder Pack 9.10 for game version 1.8.0 (official release).

I am trying to make a multiline text field similar to the game's original net.minecraft.client.gui.GuiTextField. I have a class extending GuiTextField and overriding almost all of the methods to provide multiline support. I have just about everything working the way it needs to except for rendering.

I want to render the text similarly to the swing JTextArea (where it sets a clip area then renders all the text) but I'm unsure how to do this, or if its even possible to do alongside the game's GlStateManager and WorldRenderer. After some googling I think what I'm looking for is OpenGL stencils. I made sure that the display is created with a pixel format that supports stencils (In net.minecraft.client.Minecraft I changed Display.create((new PixelFormat()).withDepthBits(24)); to Display.create((new PixelFormat()).withDepthBits(24).withStencilBits(8)); to make sure there is a stencil buffer), and have been playing around with a bit of code and so far I have gotten 2 results:

1. All other buttons on my gui (which render after the textfield) render perfectly fine, just as they should. The text field and the dirt background drawn by GuiScreen.drawDefaultBackgroudn() are all blacked out even if the stencil rectangle I draw covers them completely.
2. Everything renders just as it did before I had the stencil code.

I have a feeling that the direct calls to the GL class are conflicting with the game's render managers but with the highly obfuscated code in the render manager I have no clue. (I also know that the game's GlStateManager has inner classes called StencilState and StencilFunc, but after some Java Searches in eclipse I can only find variable declarations/instantiations, but the vars are never referenced).

Here is the code I have so far to render the text field (irrelevant code trimmed):

```
@Override
public void drawTextBox() {
    if (this.getVisible()) {

        // trimmed: create x and y variables & draw border/background of textfield
        //     border/background drawn with GlStateManager and WorldRenderer

        // stencil code I found online
        glClear(GL_DEPTH_BUFFER_BIT);
        glEnable(GL_STENCIL_TEST);
        glColorMask(false, false, false, false);
        glDepthMask(false);
        glStencilFunc(GL_NEVER, 1, 0xFF);
        glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP);  // draw 1s on test fail (always)

        // draw stencil pattern
        glStencilMask(0xFF);
        glClear(GL_STENCIL_BUFFER_BIT);  // needs mask=0xFF

        // X1 is just inside the left border
        // X4 is just inside the right border
        // Y1 is just inside the top border
        // Y4 is just inside the bottom border
        glBegin(GL_QUADS);
        glVertex3f(x4, y4, 0.0f);
        glVertex3f(x4, y1, 0.0f);
        glVertex3f(x1, y1, 0.0f);
        glVertex3f(x1, y4, 0.0f);
        glEnd();

        glColorMask(true, true, true, true);
        glDepthMask(true);
        glStencilMask(0x00);
        // draw where stencil's value is 0
        glStencilFunc(GL_EQUAL, 0, 0xFF);
        /* (nothing to draw) */
        // draw only where stencil's value is 1
        glStencilFunc(GL_EQUAL, 1, 0xFF);

        //offset drawing location of text
        GlStateManager.translate(-colViewOffset, -lineViewOffset * 10, 0.0);

        // main drawtext
        int xOff = hShadow ? 10 : 0;
        for (int lin = lineViewOffset; lin < lineViewOffset + height / 10 && lin < lines.size(); lin++) {
            fontRenderer.drawString(lines.get(lin), x, y + (lin) * 10, getEnabled() ? 0xE0E0E0 : 0x707070);
        }

        // draw text under vertical shadows
        if (vShadow) {
            if (lineViewOffset - 1 >= 0) {
                fontRenderer.drawString(lines.get(lineViewOffset - 1), x, y + lineViewOffset * 10 - 10, getEnabled() ? 0xE0E0E0 : 0x707070);
            }
            if (lineViewOffset + height / 10 < lines.size()) {
                fontRenderer.drawString(lines.get(lineViewOffset + height / 10), x, y + height + lineViewOffset * 10, getEnabled() ? 0xE0E0E0 : 0x707070);
            }
        }

        // trimmed: draw cursor

        GlStateManager.translate(colViewOffset, lineViewOffset * 10, 0.0);

        // disable stencils
        glDisable(GL_STENCIL_TEST);

        // trimmed: draw bordershadows
        //     bordershadows drawn with GlStateManager and WorldRenderer
    }
}

```

With everything I have right now this is what I get:

What can I do to my code/the games render code to only draw text inside the white/gray rectangle bordering the textfield?

# Answer
> 1 votes
Happy new years, this will solve your problem:

```
float x1 = //left bound
        float x2 = //right bound
        float y1 = //up bound
        float y2 = //down bound
        ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft());
                x1 *= sr.getScaleFactor();
                y1 *= sr.getScaleFactor();
                x2 *= sr.getScaleFactor();
                y2 *= sr.getScaleFactor();
                float temp;
                if (y1 > y2) {
                    temp = y2;
                    y2 = y1;
                    y1 = temp;
                }
                GL11.glScissor((int)x1, (int)(Display.getHeight()-y2), (int)(x2-x1), (int)(y2-y1));
                GL11.glEnable(GL11.GL_SCISSOR_TEST);

        //DRAW TEXT THAT NEEDS TO BE CLIPPED OUTSIDE THE ABOVE SPECIFIED AREA

        GL11.glDisable(GL11.GL_SCISSOR_TEST);

```

---
Tags: opengl, java, minecraft-modding, modding
---


# Question
Title: Unity Inspector | Displaying min and max variables on a single line
**In a C# Unity script, how can I add fields that will be displayed in the Unity Inspector with min and max values on a single line?** (like it is done for the Particle System, where you can choose `Between Two Constants`)

---

WHAT I HAVE | Separate lines for min and max:

```
public class MyTest : MonoBehaviour {
    [SerializeField] float projectileRateMin = 1f;
    [SerializeField] float projectileRateMax = 3f;
}

```

WHAT I WOULD LIKE: Single line with both min and max:

Another example is Vector2, which also gets displayed in the Inspector on one line. I did look at the Vector2 code and tried to copy and rename the relevant parts of the Vector2 struct to my own version, but it didn't show up in the Inspector at all.

# Answer
> 1 votes
Use the GUILayoutclass for drawing inspector and editor windows.

```
GUILayout.BeginHorizontal();
//the two lines you already have
GUILayout.EndHorizontal();

```

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


# Question
Title: Can't rotate object after using transform.forward
I'm using above code to rotate object pointing where it moves:

```
transform.forward = m_Rigidbody.velocity;

```

It works fine, however the problem is that I can't rotate this object anymore after set direction.

```
transform.forward = m_Rigidbody.velocity;
transform.Rotate(0, 0, m_RotateSpeed * Time.deltaTime * 500); // Not Working

```

Code is simple, first rotate the object to point where it goes and then rotate z axis. But when I ran the game, it just shaking little bit and didn't rotate at all.

Why it doesn't work even rotating code after the transform.forward? Any advice will very appreciate it.

# Answer
> 1 votes
`transform.forward = foo;`

is basically a shortcut for

`transform.rotation = Quaternion.LookRotation(foo, Vector3.up);`

ie. it's not turning just one component of the orientation, it's forming a whole new orientation from scratch, discarding anything that came before.

Since a single vector is not enough information to fully determine the orientation, it assumes you want the local up vector to align as best it can with the global y+ axis, `(0, 1, 0)`

When you do this every frame, and then try to `transform.Rotate()` incrementally afterwards, that incremental rotation doesn't have an opportunity to accumulate over subsequent frames. In the next frame it will just be replaced by the orientation computed from the forward vector, and you'll only ever get a single frame's worth of twist added on afterward. Since frames can vary in duration, this creates the vibration you're seeing.

So, instead you can do one of two things:

A) Track roll separately, and add it all at once.

```
m_RollAngle += m_RotateSpeed * Time.deltaTime * 500;
m_RollAngle = m_RollAngle % 350f;
transform.forward = m_Rigidbody.velocity;
transform.Rotate(0, 0, m_RollAngle);

```

B) Rotate your up vector, and form your new orientation using that.

```
var newUp = Quaternion.AngleAxis(m_RotateSpeed * Time.deltaTime * 500, transform.forward) * transform.up;

transform.rotation = Quaternion.LookRotation(m_Rigidbody.velocity, newUp);

```

---
Tags: unity, rotation, transformation
---


# Question
Title: Can you use other gamepass ids on your own Roblox game?
I'm creating a game on Roblox and I need to know if I can use other user's gamepass ids. And if I can will they work?

# Answer
If you are using another user's game pass id I don't think it will work out because only game passes created under your game will work in your game.

Edit: Only gamepasses from this page are available to use on your game: `https://www.roblox.com/develop?selectedPlaceId="`**`yourgameid`**`"&View=34`
> 1 votes

---
Tags: roblox
---


# Question
Title: Calculate angle between player and end point
I have such question:

how to calculate angle between player and end point?

Things, which i have:

1. Player. I have X, Y, Z position of player and his Z-angle (0-360)
2. Endpoint. I have only X, Y, Z position of end point.

Task:

Rotated player Z-angle to end point.

How i can did this?

Please, help :3

# Answer
If I understand you correctly, you want

```
z_angle = atan2(target_y - player_y, target_x - player_x);

```
> 2 votes

---
Tags: c#, c++
---


# Question
Title: Unity | Camera - Follow target with view port point's offset from center
Some additional remarks before I address the issue:

**How Viewports work in Unity:**

Whatever the dimensions of the screen's rect, the viewports coordinates are mapped in normalized coordinates, where 0 represents left and bottom, for x and y respectively, and 1 right and top, for x and y respectively (image below).

**Follow a Target (Easy implementation for the sake of demonstration):**

Consider this following simple algorithm to follow a target:

```
CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        transform.position = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.Lookat(target);
    }
}

```

**Issue:**

The following works as expected, but the target will always be at the viewport's center ({ 0.0, 0.0 })

**What I am trying to Achieve:**

This is what I am trying to achieve: make camera follow a given target, with an additional offset from the viewport's center. This offset being additional to the following offset applied to the target.

So for example, if I define two ranged floats, centerX and centerY respectively, I'd like the camera to be positioned with an additional offset, so the defined offset is at the target. As an example, on the image below, I have centerX and centerY on { 0.2, 0.25 } respectively, so the target should be at that viewport's point.

Having a resulting (partial) script:

```
CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;
    [Range(0.0f, 1.0f)] public float centerX;
    [Range(0.0f, 1.0f)] public float centerY;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        Vector3 destination = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.position = destination + GetCalculatedOffset();
        transform.Lookat(target);
    }

    private Vector3 GetCalculatedOffset()
    {
        // interpret the Vector { centerX, centerY } to return an offset.
        // return (interpretedOffset - target.position);
    }
}

```

**What I have already tried:**

* Make the camera position to the destination plus an offset of the center \[{centerX, centerY} - {0.5, 0.5}\], the direction is ok, but obviously, the target is not positioned at the expected viewports' point coordinate.
* Have a global vector that is the custom center point relative to the camera's transform and the nearPlane, and then make an offset between that point and the target, ignoring the z. The camera gets away from the target.

**What I am not trying to achieve:**

Something like following example (define an additional offset vector, and position the camera with the additional offset):

```
CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;
    public Vector3 additionalOffset;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        Vector3 destination = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.position = destination + additionalOffset;
        transform.Lookat(target);
    }
}

```

I mean, this technically works, since the target won't be at the center of the viewport. But the intention is for the target to be positioned at the defined viewport's point.

Any additional information you may need, let me know. Thank you beforehand, and Happy New Year.

# Answer
If you want to know which way a particular viewport point faces in the world, you can just ask the camera using the `ViewportPointToRay` method.

```
[RequireComponent(typeof(Camera))]
public class OffCenterFollow : MonoBehaviour {

    public Transform target;
    public float targetDistance;
    public Vector2 viewportPosition;

    new Camera camera;

    private void OnEnable() {
        camera = GetComponent<Camera>();
    }

    void LateUpdate () {
        var ray = camera.ViewportPointToRay(viewportPosition);

        Vector3 fromTarget = -ray.direction * targetDistance;
        if(camera.orthographic) {
            Vector3 shift = transform.InverseTransformPoint(ray.origin);
            shift.z = 0f;
            fromTarget -= transform.TransformVector(shift);
        }

        transform.position = target.position + fromTarget;
    }
}

```
> 1 votes

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


# Question
Title: How to make the player's weight deform a rope bridge?
I'm making a 2d game, and I want my character to deform my rope bridge with physics effects on the jointed structure when they walk over it.

Right now, the player can stand on the bridge, but it doesn't react to where their weight is pressing down on it:

Here's how I've configured my player avatar:

And how I've set up the segments of the bridge using hinge joints:

Finally, here's the player control script I'm using:

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

public class PlayerPlatformerController : PhysicsObject
{

    public float maxSpeed = 7;
    public float jumpTakeOffSpeed = 7;

    private SpriteRenderer spriteRenderer;
    private Animator animator;

    // Use this for initialization
    void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
    }

    protected override void ComputeVelocity()
    {
        Vector2 move = Vector2.zero;

        move.x = Input.GetAxis("Horizontal");

        if (Input.GetButtonDown("Jump") && grounded)
        {
            velocity.y = jumpTakeOffSpeed;
        }
        else if (Input.GetButtonUp("Jump"))
        {
            if (velocity.y > 0)
            {
                velocity.y = velocity.y * 0.5f;
            }
        }

        bool flipSprite = (spriteRenderer.flipX ? (move.x > 0.01f) : (move.x < 0.01f));
        if (flipSprite)
        {
            spriteRenderer.flipX = !spriteRenderer.flipX;
        }

        animator.SetBool("grounded", grounded);
        animator.SetFloat("velocityX", Mathf.Abs(velocity.x) / maxSpeed);

        targetVelocity = move * maxSpeed;
    }
}

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

public class PhysicsObject : MonoBehaviour
{

    public float minGroundNormalY = .65f;
    public float gravityModifier = 1f;

    protected Vector2 targetVelocity;
    protected bool grounded;
    protected Vector2 groundNormal;
    protected Rigidbody2D rb2d;
    protected Vector2 velocity;
    protected ContactFilter2D contactFilter;
    protected RaycastHit2D[] hitBuffer = new RaycastHit2D[16];
    protected List<RaycastHit2D> hitBufferList = new List<RaycastHit2D>(16);

    protected const float minMoveDistance = 0.001f;
    protected const float shellRadius = 0.01f;

    void OnEnable()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        contactFilter.useTriggers = false;
        contactFilter.SetLayerMask(Physics2D.GetLayerCollisionMask(gameObject.layer));
        contactFilter.useLayerMask = true;
    }

    void Update()
    {
        targetVelocity = Vector2.zero;
        ComputeVelocity();
    }

    protected virtual void ComputeVelocity()
    {

    }

    void FixedUpdate()
    {
        velocity += gravityModifier * Physics2D.gravity * Time.deltaTime;
        velocity.x = targetVelocity.x;

        grounded = false;

        Vector2 deltaPosition = velocity * Time.deltaTime;

        Vector2 moveAlongGround = new Vector2(groundNormal.y, -groundNormal.x);

        Vector2 move = moveAlongGround * deltaPosition.x;

        Movement(move, false);

        move = Vector2.up * deltaPosition.y;

        Movement(move, true);
    }

    void Movement(Vector2 move, bool yMovement)
    {
        float distance = move.magnitude;

        if (distance > minMoveDistance)
        {
            int count = rb2d.Cast(move, contactFilter, hitBuffer, distance + shellRadius);
            hitBufferList.Clear();
            for (int i = 0; i < count; i++)
            {
                hitBufferList.Add(hitBuffer[i]);
            }

            for (int i = 0; i < hitBufferList.Count; i++)
            {
                Vector2 currentNormal = hitBufferList[i].normal;
                if (currentNormal.y > minGroundNormalY)
                {
                    grounded = true;
                    if (yMovement)
                    {
                        groundNormal = currentNormal;
                        currentNormal.x = 0;
                    }
                }

                float projection = Vector2.Dot(velocity, currentNormal);
                if (projection < 0)
                {
                    velocity = velocity - projection * currentNormal;
                }

                float modifiedDistance = hitBufferList[i].distance - shellRadius;
                distance = modifiedDistance < distance ? modifiedDistance : distance;
            }

        }

        rb2d.position = rb2d.position + move.normalized * distance;
    }

}

```

# Answer
> 1 votes
I've noticed that your character's rigidbody is set to "Kinematic". A kinematic rigidbody isn't driven by the physics engine. It has no weight and thus does not exert any force on other objects it stands on. So it won't interact with your rope bridge at all.

When your player-characters rigidbody is no longer kinematic, you must no longer move it by directly changing its `rb2d.position`. When you change the position like that, you are not moving the character, you are teleporting it. That can lead to weird problems in regards to collision detection and game physics. When you are moving an object which is supposed to interact with the physics engine, always do so by adding forces to its rigidbody, or when that gets too fiddly, by changing the velocity of its rigidbody. But only change the position directly when you actually mean to make it disappear in one location and and reappear in a different location.

Also another hint about the bridge itself: connect the bridge parts using Spring Joints instead of hinge joints.

This quick PoC I just created needs some more tweaking of the rigidbody and spring settings to reduce the jitter, but it should give you an idea how it can work:

Edit: I forgot that you have a 2d project. In that case you would of course use Spring Joint 2D.

I am looking forward to playing your game.

---
Tags: unity, 2d, rope-physics, hinge-joint
---


# Question
Title: Unity3D: AI follow player script for prefab enemy?
So I am having an issue, I have an enemy prefab that is created when the new wave happens(think of Nazi Zombies from Call of Duty, same system) but every script I have found that deals with ai following player always involves a public transform variable. The issue is that the object I put in that variable in the inspector does not save with the prefab, rendering the script useless. Is there anyway I can get the enemy prefab when the enemy spawns to follow the player?

He is a script I tried and failed due to the issue:

```
    //The target player
public Transform player;
//In what time will the enemy complete the journey between its position and the players position
public float smoothTime = 10.0f;
//Vector3 used to store the velocity of the enemy
private Vector3 smoothVelocity = Vector3.zero;

private void Start()
{
}

//Call every frame
void Update()
{
    //Look at the player
    transform.LookAt(player);
    //Move the enemy towards the player with smoothdamp
    transform.position = Vector3.SmoothDamp(transform.position, player.position, ref smoothVelocity, smoothTime)*Time.deltaTime;

}

```

# Answer
A common way is to assign the tag "Player" to the player-character. The tag selector is in the Inspector just below the name input. You can then obtain a reference to that player with:

```
player = GameObject.FindWithTag("Player").transform;

```

When your player is already in the scene when the enemy is spawned, you can put that into `Start`. When the player might join the scene later or leave the scene to get replaced with another player object, you should do this in `Update` instead and handle the case that `FindWithTag("Player")` returns `null`.

Also keep in mind that when you have more than one game-object with the tag "Player" in the scene, you can't predict which one will be found by FindWithTag. If you want to allow multiple players, you should use `FindGameObjectsWithTag("Player")` which returns an array of all player game objects and then implement a logic for choosing which player to engage.
> 1 votes

---
Tags: unity, physics, ai
---


title: Getting Model View Matrix by hand

text:
# Question
Title: Getting Model View Matrix by hand
Right now I'm trying to calculate the model view matrix by hand... The App is 2D. I have something like this:

```
Vector2 Transform_GetUpVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 0;
    relative.y = 1;

    float sin = Sin(transform->angle),
        cos = Cos(transform->angle);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 Trasnform_GetRightVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 1;
    relative.y = 0;

    float sin = Sin(transform->angle),
          cos = Cos(transform->angle);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 ScreenPointToSpace(struct Application *application, DeadCamera *camera, Vector2 point)
{
    GLint viewport[4];
    GLdouble //modelMatrix[16],
             projectionMatrix[16];
    GLdouble wz1 = 0, x = 0, y = 0;
    glGetIntegerv(GL_VIEWPORT, viewport);
    //glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    Vector2 r = Trasnform_GetRightVector(camera->gameObject->transform, true);
    Vector2 u = Transform_GetUpVector(camera->gameObject->transform, true);

    GLdouble matrix[16] = {r.x, r.y, 0,      0,
                           u.x, u.y, 0,      0,
                           0,   0,   1,      0,
                           -camera->gameObject->transform->position->x / 1000, -camera->gameObject->transform->position->y / 1000, 0, 1 };

    GLint realy = viewport[3] - (GLint)point.y - 1;
    gluUnProject((GLdouble)point.x, (GLdouble)realy, 0, matrix, projectionMatrix, viewport, &x, &y, &wz1);
    Vector2 s;
    s.x = (float)x * 1000;
    s.y = (float)y * 1000;
    return s;
}

```

But When I rotate the camera, the matrix is wrong.... why?

As you can see in this image the hammer cursor means that the cursor is touching a red circle area.

But When I rotate the camera everything is at the wrong screen locations.

# Answer
Ok Found a Way.... I was calculating the vectors incorrectly the angle should be converted. But I still don't get the matrix part... but here it goes

```
Vector2 Transform_GetUpVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 0;
    relative.y = 1;

    float sin = sinf(transform->angle * 3.14f / 180),
          cos = cosf(transform->angle * 3.14f / 180);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 Transform_GetRightVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 1;
    relative.y = 0;

    float sin = sinf(transform->angle * 3.14f / 180),
          cos = cosf(transform->angle * 3.14f / 180);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 ScreenPointToSpace(struct Application *application, DeadCamera *camera, Vector2 point)
{
    GLint viewport[4];
    GLdouble //modelMatrix[16],
             projectionMatrix[16];
    GLdouble wz1 = 0, x = 0, y = 0;
    glGetIntegerv(GL_VIEWPORT, viewport);
    //glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    Vector2 r = Transform_GetRightVector(camera->gameObject->transform, true);
    Vector2 u = Transform_GetUpVector(camera->gameObject->transform, true);

    GLdouble matrix[16] = {r.x, u.x, 0,  0,
                           r.y, u.y, 0,      0,
                           0,   0,   1,      0,
                           -camera->gameObject->transform->position->x / 1000, -camera->gameObject->transform->position->y / 1000, 0, 1 };

    GLint realy = viewport[3] - (GLint)point.y - 1;
    gluUnProject((GLdouble)point.x, (GLdouble)realy, 0, matrix, projectionMatrix, viewport, &x, &y, &wz1);
    Vector2 s;
    s.x = (float)x * 1000;
    s.y = (float)y * 1000;
    return s;
}

```
> 0 votes

# Answer
Edit2: Added more information with examples and fixed a typo.

I believe this should resolve some of your problem and it'll reduce your code quite a bit.

You can replace all that you had in that answer post with the following:

```
Vector2 ScreenPointToSpace(struct Application *application, DeadCamera *camera, Vector2 point)
{
    GLint viewport[4];
    GLdouble //modelMatrix[16],
             projectionMatrix[16];
    GLdouble wz1 = 0, x = 0, y = 0;
    glGetIntegerv(GL_VIEWPORT, viewport);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    float radians = ((camera->gameObject->transform->angle) * 3.14f) / 180;

    float sin = sinf(radians),
    float cos = cosf(radians);

    GLdouble matrix[16] =
    {
    cos, sin, 0,  0,
    sin, cos, 0,  0,
    0,   0,   1,  0,
        -camera->gameObject->transform->position->x / 1000, -camera->gameObject->transform->position->y / 1000, 0, 1
    };

    GLint realy = viewport[3] - (GLint)point.y - 1;
    gluUnProject((GLdouble)point.x, (GLdouble)realy, 0, matrix, projectionMatrix, viewport, &x, &y, &wz1);
    Vector2 s;
    s.x = (float)x * 1000;
    s.y = (float)y * 1000;
    return s;
}

```

In your code you were doing the following:

```
    cos, sin, 0,  0,
    -sin, cos, 0,  0,

```

To give you an idea 0 Degrees would make it

```
1, 0, 0, 0
0, 1, 0, 0

```

Looks okay... since it matches the identity matrix.

But if you do let's say 45 degrees.

You would want to have

```
0.707, 0.707, 0, 0
0.707, 0.707, 0, 0

```

But you'll get the following instead.

```
 0.707, 0.707, 0, 0  //45 Degree Right Vector.
-0.707, 0.707, 0, 0  //225 Degree Up Vector.

```
> 0 votes

---
Tags: opengl, mathematics, c
---


# Question
Title: Optimally syncing AI movement over network
I have a server with a NavMesh component that moves a bunch of NavMeshAgents in the scene and I want to sync their movement to connected clients. I'm expecting a huge amount of AI controlled characters, so I want a way that requires as few updates as possible.

Here's my initial approach: I separated linear velocity and angular velocity. When the velocity changes (I set up a threshold so that it only syncs when the change is significant), I send an update to clients so they update their velocity, then they calculate their new position based on the last synced velocity in their update function. I do the same thing for angular velocity and I update the character's rotation in the update function.

I was also planning to send a full sync of the character's position + rotation at a certain time interval to correct any major errors in movement.

It works okay for the linear velocity, but the rotation is not precise enough, so the character gets out of sync very quickly.

Do you have ideas on other approaches I could try? Or ways to improve my current approach?

We're not using Unity high level networking, we're building from the Unity Network Transport.

# Answer
This is a prediction problem, 1st order dead reconning (velocity and position/orientation) is not ideal for AIs.

I would simulate AI's on all clients, and periodically send corrections (velocity position/orientation). This is very similar to what you have tried, but the difference is that the prediction should be much more accurate. To smooth things out, you could interpolate the corrections between sends, but to start with, try direct updates to see how it works.
> 0 votes

---
Tags: unity, networking
---


# Question
Title: Why do I have to set my Unity app to full-screen manually on my phone
When I open my unity app it doesn't go full-screen until I change it in the settings, isn't there a way to do that... it actually isn't a scaling problem or an aspect ratio.... Because you can see how in the phone settings it is turned off Thanks in advance

# Answer
On Android platform you can use manifest merge trick. According to the question you need fullscreen app, so i can suggest to create your own .aar (android plugin, like jar but can contain resources such as styles) and add your own style. Then you can use it in your unity android manifest.

1. After created an empty android plugin according to the documentation, we need also create new style in styles.xml.

```
<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>

```

2. After that you need to mention this theme in your manifest file in Plugins/Android directory of your unity project

    android:theme="@android:style/Theme.AppCompat.Light.NoActionBar.FullScreen"

or you can use more simplier variant that don't need to resolve dependencies from resolver of app compat library (see)

```
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"

```

So in conclusion you need to know android platform and how to create android plugins and connect it in unity project
> 0 votes

---
Tags: unity
---


title: Replace vector3 list with object list?

text:
# Question
Title: Replace vector3 list with object list?
In this script I respawn a group of enemies in different places. To choose those places I have to put manually position value. I need to change this with object.

```
    [SerializeField]
List<SpawnEnemy> objectsToSpawn;

void Update()
{

    for (int i = objectsToSpawn.Count - 1; i >= 0; --i)
    {
        SpawnEnemy so = objectsToSpawn[i];
        so.TimeCount += Time.deltaTime;
        if (so.TimeCount >= so.time)
        {
            so.TimeCount -= so.time;
            Instantiate(so.star, so.spawnLocation[0], Quaternion.identity);
        }
    }

}
}

[System.Serializable]
class SpawnEnemy
{
 public GameObject star = null;
 public float time = 1;
 public float TimeCount = 0;
 public Vector3[] spawnLocation; // change from vecrtor3 to gameobject or transform
}

```

# Answer
I solved. Just change...

```
public Vector3[] spawnLocation;

```

to

```
public Transform[] spawnLocation;

```

and then you can Instantiate using..

```
 Instantiate(so.star, so.spawnLocation[0].transform.position, Quaternion.identity);

```

Done... Thank you.
> 1 votes

---
Tags: unity, vector
---


title: Screen record in unity3d

text:
# Question
Title: Screen record in unity3d
How to do screen record in unity? I want to record my screen(gameplay) during my running game. That should be play/stop , replay , save that recording on locally from device, open/load from my device (which is already we recorded).

In my game one camera which can capture native camera, and one 3d model.

I wish to record that both and use my functionality whenever i want.

Thank you in advance.

# Answer
> 0 votes
I would suggest you look into Brackey's Rewind Tutorial and improve upon that. One thing you could do is you can store all the positions in a JSON file or your own format when you/player hits stop button and read from that format when replaying, also he is rewinding and not replaying so you need to store the position in reverse order than him, or you can read in different order. He also addresses some limitations with this method like it'd be silly to store game play of more than a few seconds as it takes up a lot of memory to track every object, another thing he addresses is that not every device runs on same frame rate so replays will be different on different devices.

Also here's a wild thought, if your game is not fast-paced than you could record your object's position every x frames and maybe Lerp between those values when replaying? It won't be as accurate but it'll be performant than storing each positional change. By doing this you can probably get around the "different frame rate" limitation cause it'll be same on every device as it's "recreating frames", and with this you can also record more game play as it won't need as much memory.

---
Tags: unity, unityscript
---


# Question
Title: How do i prevent IAP abuse using restoring purchases in an online game?
Lets say i have a mobile mmorpg (ios/android) where you can purchase premium currency using IAP's... how do i actually prevent the following case :

* Player purchases premium currency
* Server side checks if the purchase is valid, grants the user premium currency
* Player uses the premium currency to buy some items
* Player restores his purchase on google play and gets his money back

Result : Player didnt spended money and still got what he wanted

As long as i know theres no option to prevent that case in google playstore or ios app store... Users can restore purchases within 48 hours after the purchase.

So what could i basically do to prevent this, aslong as i dont use 3rd party payment services like PayPal ?

# Answer
One way to prevent this is by tracking user's purchases on back-end/server and saving the game state when the user purchased the item along with the Order Id and pacakge name for every purchase, then if the user restores the purchase within 48 hours (which you can check using Void Purchases API) then just restore the game state to the saved one and if the player doesn't issue a restore request then delete the saved state from the server.

Here's the reference article from Google: Protect your apps from refund abuse
> 2 votes

---
Tags: android, game-design, multiplayer, game-mechanics, mmo
---


# Question
Title: What bones are involved in a walk cycle like Leon's in RE4?
I would like to create a character that moves like Leon in RE4. This video demonstrates Leon's walk cycle, which I'd like to reproduce. I'm confused about which bones of my character's skeleton should be rotated to achieve the desired cool "sideways" look.

At first I thought that his feet and hip are not rotated at all and that only his abdomen was rotated. But after watching the above video (for example at 00:20) where a camera FOV hack was applied and one can finally see his lower body, I'm not sure anymore.

How has this walk cycle been created? Did they take a walk-straight-forward-animation and then rotated some bones? If yes, which ones? I guess somebody who has a great eye for animations can see that.

Thank you.

# Answer
Leon's body position here is a fairly common martial pose: it lets him present less of a forward-facing target and provides stability by lowering his center of gravity and allowing him to more easily shift his weight in any direction.

While you could try to reproduce this by only animating the upper body, you should only do so if your character literally has no lower body. Real humans, unlike video game humans, are not a series of disconnected bones. Muscles and tissue hold them together and apply constraints to the range of motion of any individual piece.

Simply rotating the character's torso but leaving the legs unchanged, as if the character is just walking forward, will look weird because real human body's aren't tanks.

To get into that pose, a real human needs to rotate the hips. A counter-rotation of some kind to the legs, arms and neck, so the hands, feet and head face forward to varying appropriate degrees, is then required. The knees have to bend to lower the center of gravity, as well.

Probably the short answer to your question is "all or most of them," but without seeing your actual rig and the problems you're currently having getting the look you want, it's going to be hard to provide more specific guidance.
> 1 votes

---
Tags: animation
---


# Question
Title: Should I throw out game heavily using OpenGL 2.0 and rewrite it from scratch?
I've picked up one old open source game (done with C++/Lua) with a lot of features and chosen to continue its development. It use SDL2 (ported by me from 1.2) and OpenGL 2.0. Now when I look at futher development it seems that mobile platforms don't support legacy OpenGL stuff, which is used really heavily: entire arhitecure is based on calling gl functions from lua side, where rendering functions are specified.

I'm not quite a pro in 3D development, so I'm not sure is it easier to change current architecture to modern OpenGL or re-write all the stuff. There are some other architecture problems (not GL related ones).

So, is it better to try changing exsisting architecture or start all from scatch, using modern stuff like OpenGL 3.1+ or Vulcan?

# Answer
Depending on your situation this may be a matter of preference. That being said, we can attempt to break the problem down somewhat objectively.

First off, you mentioned a concern about mobile platforms not supporting legacy OpenGL. Objectively, you can re-frame that as:

* Will the existing game engine currently work on your target platforms?

If the answer is no, then either you need to rework / replace the engine OR adjust to target platform expectations.

If the answer is yes, then the next thing to consider is:

* Will the engine work on the target platforms for the duration that you expect to support the game?

Again, if the answer is no, then either you need to rework / replace the engine OR adjust to your expectations regarding how long the game will be viable.

There are some other factors you may wish to consider. If your personal goal is to learn modern OpenGL, then sinking time into a legacy development doesn't make sense. And as pointed out in the comments, transitioning the engine to use modern OpenGL might be easier than rewriting it from scratch.

Finally, while modern OpenGL is likely to be more performant for modern games and the demands they place on GPUs, modern video cards are typically fast enough to handle the legacy OpengGL from older games, in part due to the fact that the graphics expectations were lower. If those expectations aren't good enough for you (i.e. you want to render the game in 4k, use high resolution textures, support VR, etc) then you'll need to weigh the expense of finding ways to execute those objective in legacy OpenGL against the expense of porting or rewriting to support the modern APIs.
> 1 votes

---
Tags: opengl, architecture
---


# Question
Title: Unity - Transform.RotateAround() + Transform.Translate() - Why is rotation offset created and how can it be fixed?
I have one object orbit another with RotateAround(), then I use Translate() to move the orbiting object in the same frame in an effort to change the distance at which the object is orbiting. This causes the rotation provided by RotateAround to drift. How can this drift be corrected without rewriting my own RotateAround?

```
public class TestRotateAround : MonoBehaviour
{
    [SerializeField]
    Transform orbitTarget;

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

    }

    // Update is called once per frame
    void Update()
    {
        Vector3 dirToTarget = (orbitTarget.position - transform.position).normalized;

        transform.RotateAround(orbitTarget.position, Vector3.forward, 10 * Time.deltaTime);

        transform.Translate(-dirToTarget * Time.deltaTime * 2);
    }
}

```

# Answer
Remember, `Transform.Translate` operates in local coordinates by default, but your `dirToTarget` variable is in world coordinates.

So, you can fix this by...

1. Adding `Space.World` to your translation
2. Re-ordering your code so that you rotate *after* computing your vector and translating along it, or *before*, not in-between the two steps.

Like so:

```
void Update()
{
    Vector3 dirToTarget = (orbitTarget.position - transform.position).normalized;
    // If we rotate between these two lines, then the "to target" direction we
    // computed above won't be the correct "to target" direction anymore,
    // since we've rotated around the target and it's in a different direction now.
    transform.Translate(-dirToTarget * Time.deltaTime * 2, Space.World);

    // So instead we'll do our rotation at the end.
    transform.RotateAround(orbitTarget.position, Vector3.forward, 10 * Time.deltaTime);
}

```

Or, here's an alternative formulation with no `RotateAround`/`Translate`, showing the underlying vector & quaternion math that's going on under the hood:

```
void Update() {
    Quaternion rotation = Quaternion.AngleAxis(10 * Time.deltaTime, Vector3.forward);
    transform.rotation *= rotation;

    Vector3 toTarget = (orbitTarget.position - transform.position);
    Vector3 newOffset = -toTarget - 2 * Time.deltaTime * toTarget.normalized;

    transform.position = orbitTarget.position + rotation * newOffset;
}

```
> 1 votes

---
Tags: unity, transformation
---


# Question
Title: Do I need to add an anti-piracy system to my game if I publish on Itch.io?
Do I need to add an anti-piracy system to my game if I decide to publish it on itch.io or a similar marketplace? The investment to add that system is small, because it's a simple serial code generator.

# Answer
# Don't worry about piracy

Two main reasons:

1) Your game isn't popular enough. (If it is, then it won't be in itch.)

2) You can't do anything about it anyway. (Even major publishers haven't solved this problem with a billion dollars)

But really, it's all about reason 3: people who like your game are going to be generally altruistic. If they did acquire it for free and decide "wow, this is really good" they'll want to support the development. And how do they do that? They send you money. Surprise, now they've paid for your game.

If they don't pay for it, then it isn't something they would have paid for anyway, and in fact, would have been less likely to pay for it with money that wasn't even theirs if they couldn't have gotten it any other way.

Think about it like watching a crappy movie. Sure, you rented it for a dollar from RedBox, but that dollar went more to supporting *RedBox* because you like their business model. That movie want one that you would have gone to see in a theator, *even if you'd snuck in and saw it for free.* A good movie you didn't expect to be awesome? Well, now you start paying attention to the director and go see his next film opening night. Or at least, at the theator. Or rent all his other films. And tell your friends about it, and they go rent his films, and so on.

Pirates pirate not because they want things for free, but because they know that 90% of everything is crap and don't want to support it *before* finding out which things are crap and which aren't. If your thing isn't crap, they'll pay for it afterwards (one way or another, even if it's just telling their friends who all come to itch and pay you $2 for your thing: $2 lost, $10 gained).

I've, more than once, pirated something only to turn around and buy three copies to give away to friends. No joke. Once I found a game called Dragon Warrior Monsters, downloaded a rom to see what it was. Kind of "pokemon in the Dragon Warrior ongoing rpg series" kind of game, played the hell out of it. Sometime later my local video game outlet across the street from my high school had 8 copies come in. I bought one that afternoon, convinced my friend who was standing next to me to buy one, convinced a second friend the next day, *and then bought two more to give to two other friends the day after.* by the end of the next week all 8 copies were gone and I was responsible for 5 of them. I still know where my copy is, although its save battery has since died.
> 6 votes

# Answer
If your game is offline, and is a simple zipped file, that means if someone downloads it they can send it to other people, which means the average person can "pirate" it.

Do you "need" to put anti-piracy protection? This depends on what you want to achieve. Adding protections most likely means the game needs to "phone home" or needs an internet connection to play even the offline parts, which I personally find very frustrating on games, and I assume others do too.

However people want to sell their games and earn the money they deserve, so there's not many other choices.

Having said that, also keep in mind that piracy can increase the popularity of an otherwise small game. There are hidden gems out there that never managed to become popular even they they deserved it. This means that there are cases (although I don't know how often) where people would earn X amount of money, but because people pirate their content and it becomes more popular, they earn more money, from the people that actually buy it.

To sum it up, do you need to add anti-piracy protection? If you care about profit and do not want anyone playing your game without buying it first, then probably yes.
> 4 votes

---
Tags: piracy
---


# Question
Title: Can't get AABB Collision to work properly
This is the code I'm using to resolve collisions on the players left side. It works when I'm on the ground, but if I'm falling, it does not work.

```
public static boolean onWall(Rectangle rect1, Rectangle rect2){

    if(rect1.x > rect2.x && rect1.x <= rect2.x + rect2.width && ((rect1.y > rect2.y && rect1.y < rect2.y + rect2.height) || rect1.y + rect1.height > rect2.y && rect1.y + rect1.height < rect2.y + rect2.height)){
        rect1.x = rect2.x + rect2.width;
        return true;
    }

    return false;

}

```

# Answer
Sorry finally figured it out, heres my code just in case anyone else needs help

```
public static boolean yCollision(Rectangle p, ArrayList<Rectangle> a, Vector2 v){
    for(Rectangle r: a){
        if(p.y + v.y <= r.y + r.height && ((p.x > r.x && p.x < r.x + r.width) || (p.x + p.width > r.x && p.x + p.width < r.x + r.width)) && p.y > r.y + (r.height / 2)){
            p.y = r.y + r.height;
            return true;
        }
        if(v.y > 0){
            if(p.y + p.height + v.y > r.y && p.y + v.y + p.height < r.y + r.height && ((p.x > r.x && p.x < r.x + r.width) || (p.x + p.width > r.x && p.x + p.width < r.x + r.width)) && p.y > r.y){
                p.y = r.y - p.height;
                return true;
            }
        }
    }
    return false;
}

public static String xCollision(Rectangle p, ArrayList<Rectangle> a, Vector2 v){
    for(Rectangle r: a){
        if(p.x + v.x <= r.x + r.width && p.x + v.x >= r.x && ((p.y > r.y  && p.y < r.y + r.height) || (p.y + p.height > r.y && p.y + p.height < r.y + r.height))){
            p.x = r.x + r.width;
            return "left";
        }
        if(p.x + p.width + v.x >= r.x && p.x + p.width + v.x <= r.x + r.width && ((p.y > r.y  && p.y < r.y + r.height) || (p.y + p.height > r.y && p.y + p.height < r.y + r.height))){
            p.x = r.x - p.width;
            return "right";
        }
    }
    return "none";
}

```
> 1 votes

---
Tags: java, 2d, libgdx, collision-detection, aabb
---


title: How to develop custom Unity graphics?

text:
# Question
Title: How to develop custom Unity graphics?
Processing is a Java library for working with computer graphics, providing methods by which to draw primitive objects, custom meshes, etc., as well as mathematical methods (such as Simple Harmonic Motion) by which to animate and control them.

p5.js is an equivalent library for JavaScript and working with graphics on the web. You also have openFramworks which is similar but for C++.

How can you achieve similar graphics capabilities in the Unity Game Engine?

Suppose, for example, I wanted to build a game like Duet. I can imagine how I might go about creating those graphics in Processing or p5.js, but not in Unity and C#. How can you have that kind of creative freedom to build and draw in Unity?

Thanks.

# Answer
This is a really broad question. Unity is a very powerful and feature-rich game engine. It provides you with several tools which can help you to create unique procedural graphic effects:

* Programming your own shaders gives you a lot of freedom to develop graphic effects on the GPU
* The Mesh class gives you access to the vertex and UV coordinates of your 3d models. You can use it to deform or even generate new 3d objects at runtime.
* The methods GetPixels and SetPixels of the class Texture2D allow you to procedurally change or generate textures from C# scrips. But keep in mind that real-time image manipulation like that should better be done on the GPU than on the CPU. When you are going to change a texture every frame, you should rather be doing this with a shader for performance reasons.

And then there is of course a lot of cool stuff you can do with the special effect tools Unity provides to you out-of-the-box:

If I would want to copy Duet in particular, I would do the trails of those red and blue balls with trail renderers. For the after-image of the blocks I would try the motion blur post-processing effect first and when that doesn't give me the effect I want I would use particle effects to generate fading clones of the same sprite used for the block. Those background animations could be done by creating a couple of sprites and animate their transforms with the animation system. When I run into performance problems due to having too many game objects, I would switch to the new Entity - Component - Systems architecture for the background objects.
> 1 votes

# Answer
making a game like duet should be easily done using unity 2d game objects but any simple art program could make those too and they can be imported into unity as an asset. and if you ever run into a situation where what you want to make is outside your ability i highly reccomend the asset shop on the unity site as people put up graphics and code all the time and some of it is available to be used for free.
> 0 votes

---
Tags: unity, graphics, graphics-programming, graphic-effects, processing
---


# Question
Title: Changing Hitbox from a single spritesheet
I have different animation in a single spritesheet. I wonder how do you guys assigning these hitboxes?

# Answer
> 1 votes
I do not recommend to put sprites of different sizes in one file.

As example, my movement animation is e.g. 64x64px and my attack animation is 96x96px. Therefore I have one file for the movement animation and one for the attack animation.

May sound to produce some clutter but in fact it is better to seperate those animation. Imagin if you want to have different animations for different actions (e.g. wielding a huge axe compared to fire a gun) If you put everything into one file with different frame sizes it will probably end up beeing a mess.

---
Tags: c#, 2d, monogame
---


# Question
Title: Using Unity's `transform.translate()` to translate relative to an object but only using two axis
I'm using `transform.translate()` to move an object around the world space, relative to the camera that is following it. The camera has an angle of 23 degrees on the X axis.

The problem is that when I move forward the object tries to go into the ground and when going backward the object starts jumping because of the angle of the camera. What I want to do is freeze the Y axis of the object However if I did this the object would no longer be able to jump.

The other solution to this would be to write a method which rests the object to the ground when not jumping but them if the object was jumping and going backwards it would go flying backwards again.

How do I solve this issue?

# Answer
> 1 votes
Figured it out. Essentially i'm taking the position of the object before and after then taking the difference of both of then then adding it back into the position, so that the difference in Y-axis position that is introduced from the camera transform.Translate() is compensated for.

```
//compensate for the rotation of the camera while moving
void CompensateTransform(float X, float Y)
{
    float diffrence = transform.position.y;
    transform.Translate(speed * Time.deltaTime * X, 0,
            Time.deltaTime * Y * speed, camera.transform);
    diffrence -= transform.position.y;
    transform.position = new Vector3(transform.position.x,
        transform.position.y + diffrence,
        transform.position.z);
}

```

# Answer
> 1 votes
Here's a method that won't foreshorten your forward & backward movement:

```
Quaternion GetGroundFrame()
{
    // You can replace this with a raycast if you have more complex levels,
    // to get the direction of the collision plane under the character.
    Vector3 groundNormal = Vector3.up;

    transform cam = Camera.main.transform;

    // Construct a rotation that points your nose away from the ground,
    // and your chin roughly toward the camera's forward direction.
    Quaternion frame = Quaternion.LookRotation(groundNormal, -cam.forward);

    // Note that this will need a little special handling if your camera
    // can ever look nearly straight up/down along the ground normal.

    // Rotate the coordinate frame 90 degrees forward.
    frame = frame * Quaternion.AngleAxis(90f, Vector3.right);

    return frame;
}

```

(See more on the derivation of this coordinate frame here)

Then you can do something like:

```
Quaternion frame = GetGroundFrame();
Vector3 offset = new Vector3(r, 0, f) * speed * Time.deltaTIme;

// Multiplying by frame transforms the movement-space offset
// into worldspace.
transform.translate(frame * offset, Space.World);

```

# Answer
> 0 votes
you should simply use transform.position += vector3.forward * speed * time.deltatime;

make a variable of type float for speed like below: private float speed = 2f;

also use vector3.back or vector3.right and so on... for other directions

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


title: unity input controls

text:
# Question
Title: unity input controls
so im going through the roll a ball tutorial for unity and ive gotten though setting up all the controls to allow my ball character to move around the space ive built. but the tutorial says nothing about setting up what buttons trigger the movement. i found out where the input settings are for each axis and ive tried messing around in there but no matter what i do nothing seems to make my ball start moving around its little platform. does anyone know how to fix this issue?

# Answer
> 0 votes
By default, the game player window inside the Unity editor, and built game executables, will receive and process input only when they have focus.

To ensure your game has focus, click inside its window.

Unity gives the game window focus automatically when you hit the "Play" button to test your game, but if you accidentally click outside of it or go modifying stuff in the inspector, it can lose focus and make your input seem to stop. Clicking back in fixes it.

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


title: Use OverlapSphere to fill a list?

text:
# Question
Title: Use OverlapSphere to fill a list?
I'm trying to fill a list with objects by using OverlapSphere. Any Object with tag "enemy" goes in OverlapSphere radius put it in the list. This object goes out remove it from the list.

```
public GameObject[] listEnemy;

void Update()
{
 Collider[] hitColliders = Physics.OverlapSphere(gameObject.transform.position, 2);
    foreach (Collider hitCol in hitColliders)
    {
        if (hitCol.CompareTag("enemy"))
        {

            //// evey object with tag "enemy" put in the listEnemy.

        }
    }
}

```

# Answer
> 1 votes
These are not the right tools for the job you're describing.

If you want to incrementally add & remove tagged objects as they enter & leave a spherical region, you more likely want to use an object with a SphereCollider set to IsTrigger, with a script something like this what's below, taking advantage of the inside/outside state tracking the physics engine can already do for us.

```
List<GameObject> enemiesInRange = new List<GameObject>();

void OnTriggerEnter(Collider other) {
    if(collider.CompareTag("enemy"))
       enemiesInRange.Add(other.attachedRigidbody.gameObject);
}

void OnTriggerExit(Collider other) {
    if(collider.CompareTag("enemy"))
       enemiesInRange.Remove(other.attachedRigidbody.gameObject);
}

```

If your enemies have multiple colliders, then you'll need some additional care to ensure you add/remove them only once even if you get multiple trigger enter/exit messages.

If your trigger zone moves, be sure it has a Rigidbody to move with so that the trigger enter/exits are detected & handled correctly, and to avoid unnecessary re-computation of static triggers.

You can of course make this more efficient by putting your enemies on an "Enemy" layer, and putting the trigger on an "EnemyDetector" layer that only interacts with the "Enemy" layer. That way you only ever consider collisions between the trigger and enemies, not other stuff in your scene, so there are fewer false positives to process and you can skip the tag check entirely.

---

If you prefer to use this with an OverlapSphere query, then adding/removing incrementally is likely more work than it's worth, and you can just generate the collection from scratch.

```
public float radius;
public LayerMask enemyLayers;

Collider[] nearbyEnemyColliders = new Collider[MAX_NEARBY_ENEMIES];
int nearbyEnemyCount;

void Update() {
    // Using the NonAlloc version to avoid creating garbage every frame.
    nearbyEnemyCount = Physics.OverlapSphereNonAlloc(
                         transform.position,
                         radius,
                         out nearbyEnemyColliders,
                         enemyLayers
                       );

    for(int i = 0; i < nearbyEnemyCount; i++) {
        if(nearbyEnemyColliders[i].CompareTag("enemy"))
            continue;

        // False positive.
        // Replace it with the last item in the collection and try again.
        nearbyEnemyCount--;
        nearbyEnemyColliders[i] = nearbyEnemyColliders[nearbyEnemyCount];
        i--;
    }

    // Now the first nearbyEnemyCount entries of the array
    // are all valid hits with the right tag.
}

```

Again, filtering your `enemyLayers` here can save you the false positives and let you consume the results directly, rather than doing an extra array walk to prune based on tag matches.

This array processing is also amenable to phrasing as a LINQ query, but I'll leave that for another answer if someone wants to show that style. :)

---
Tags: unity
---


title: Weighted random events with conditions

text:
# Question
Title: Weighted random events with conditions
I'm building a system for distributing ingame events for a strategy game. The game is heavily driven by the events and each country/player should receive one or more per time unit.

The algorithm is similar to the "The Soft-coded Probabilities Solution" from this question: How do I create a weighted collection and then pick a random element from it?

The main differences are:

1. I need conditions for if events can happen or not, like only triggers if unrest is above 2% or if you are at war etc. Maybe half the events will have conditions (but this may change over time as more are added while the algorithm probably won't).
2. I need a mechanism to prevent the same event repeating for the same player in too short a time period. This applies to some events but not all.

It seems that no matter how I go about this I have to do either a lot of condition checking in advance to maintain my list(s) or a lot of iteration over events that are anyway not selectable. So is this algorithm still a good choice to build upon in this case or should I be looking elsewhere?

# Answer
> 2 votes
I recommend this plan:

1. Check conditions, create a list of eligible events. Don't add event if it is the same as the one most recently shown to the user.
2. Assign weights to each event. E.g. `Event[0].weight = 5; Event[1].weight = 10;`
3. Get random number from 0 to N - 1, where N is the sum of all weights.
4. Check if the random number is less than Event\[0\].weight. If so, choose that event. Else, subtract Event\[0\].weight from the random number. Then check Event\[1\].weight and so on.
5. Once an event is selected, store it so the next time you pick one, you can keep it out of the list.

# Answer
> 0 votes
As I was writing this I arrived at an answer that seems "good enough" for me even if not necessarily the best one so adding it separately instead of in the question.

My thinking right now is to put everything into the list and only check the conditions after selecting from it. Then if necessary reselect until I get a valid event. This will also let me reuse the the same list to "draw" events for several countries even if conditions differ.

A sleep time is added per event (which can be 0). But rather than actually sleeping the event (as in removing it from the selectable list) it stays in the list and a check is made during condition evaluation if this country had the event inside the timer value.

As long as there is at least one event with no condition and no sleep time this will not create an endless loop.

---
Tags: algorithm, random
---


# Question
Title: Using DLL's for a cross-platform Unity Game
Just a quick theoretical question so I don't hit a landmine further down development. In my current project, I have quite a lot of dll's that I made myself for use in Unity. If I were to develop for Android, would these dll's still function or is there another library format that Unity prefers to use? Basically, I'm looking for a rundown of all the ways you have to import libraries into Unity for use on a specific platform. For example,

1.) .dll files. Can you use them on other platforms?

2.) If not, how would I have to recompile code to allow me to access it the same way I currently do on a different plaform?

# Answer
DLLs are Microsoft's implementation of the idea of a "shared library." You can only use them on platforms that, in some fashion, implement support for them.

In general, this means that *no*, you can't just take the DLL files you have and use them on Android, or on a macOS installation, or whatever.

Now, things like .NET and Mono are capable of reading PE files (the format of DLLs) and executing any managed code contained therein, so if your DLLs are, specifically, managed (which sounds like a possibility given what you've said about using Unity), they'll work on any platform that the appropriate version of Mono would work. Provided you don't call into any OS-specific or platform-specific stuff in them, et cetera. So there's a possibility, but it really depends on what you've written in those DLLs. You'll probably just need to test it and see.

If the DLLs are built from native code, however, you'll have to recompile them for the new target platforms into formats appropriate for those platforms. The specifics of doing so depend on the code you've written and the platforms you want to additionally target. It may simply be a matter of using the right compiler, but it may also involve writing interop stubs or something similar.
> 1 votes

---
Tags: unity, dll
---


# Question
Title: 2D Rotation of an object along a curve line
I would like to rotate an object along a curve. I managed to move the object along the curve using bezier curve algorithm. The hard part is to rotate the object constantly(no limit on maximum angle), and have to land at the end position. The angle have to be multiply of 360 when it land on the end position. A good example would be Maplestory, the item is dropped when a monster is killed. The item is rotated constantly and it will always landed at the correct angle. Start position and End position will be provided, as is used by the bezier curve algorithm, is there any algorithm for the rotation part?

# Answer
First, choose your starting and ending angles by any method you choose (they could be fixed constants, or one or both could be randomized or computed from the other...)

Next, compute the angular difference between them, wrapped to +- 180 degrees. eg...

```
float angleDifference = fmod(endAngle - startAngle + 900.0f, 360.0f) - 180.0f;

```

Next, when you compute your new position using a parameter `0 <= t <= 1` passed as an argument to your Bezier curve function, use the same parameter to interpolate your angle:

```
position = EvaluateBezier(startPosition, controlPoint, endPosition, t);
angle = fmod(startAngle + t * angleDifference + 360.0f, 360.0f);

```

This ensures you rotate at a constant rate over the course of the motion, and end with the angle exactly at your desired `endAngle`.

If you prefer to have the motion ease out, you can do so by applying the easing function of your choice to the parameter `t` before using it to interpolate your angle.
> 1 votes

---
Tags: c++, 2d, rotation, beziers
---


# Question
Title: How can I transform a world space point to a camera's screen coordinate?
I'm trying to transform a point in fragment shader from world space to screen coordinate of a second camera. Not the main one.

I think I know how to achieve that to the main camera, but I'm struggling to find an easy way to transform a point in world space to screen coordinate of camera2.

# Answer
> 1 votes
First, we can make a shader that exposes a variable for the view-projection matrix of the camera we want to project "into"...

```
struct appdata
{
    float4 vertex : POSITION;
};

struct v2f
{
    float3 worldPosition : TEXCOORD0;
    float4 vertex : SV_POSITION;
};

sampler2D _MainTex;

// Here we've defined a new variable we can put
// our second camera's projection info into.
float4x4 _CameraMatrix;

v2f vert (appdata v)
{
    v2f o;
    o.vertex = UnityObjectToClipPos(v.vertex);
    o.worldPosition = mul(unity_ObjectToWorld, v.vertex).xyz;
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    // Map world position into camera's projected coordinates.
    float4 projected = mul(_CameraMatrix, float4(i.worldPosition, 1.0f));

    // Perform perspective divide and adjust range
    // from NDC's -1...1 to UV space's 0...1
    float2 uv = (projected.xy / projected.w) * 0.5f + 0.5f;

    // Sample a texture with this UV to prove it works.
    fixed4 col = tex2D(_MainTex, uv);
    return col;
}

```

Next, we attach a script to that camera to tell it to upload its matrix into that variable each frame before rendering time:

```
[RequireComponent(typeof(Camera))]
public class PerspectiveToShader : MonoBehaviour {

    public Material materialToModify;
    public string matrixVariableName;

    new Camera camera;
    int matrixVariable;

    void OnEnable () {
        matrixVariable = Shader.PropertyToID(matrixVariableName);
        camera = GetComponent<Camera>();
    }

    void LateUpdate () {
        var viewProjection = camera.nonJitteredProjectionMatrix * transform.worldToLocalMatrix;

        materialToModify.SetMatrix(matrixVariable, viewProjection);
    }
}

```

If you need this across many materials, you can instead set it with Shader.SetGlobalMatrix instead of piping it into each material individually.

---
Tags: unity, shaders
---