# Question
Title: How can I find and get all enabled cameras and switch between them?
I have 5 cameras in the scene. In the Inspector I added to the cameras array 3 cameras. In the script I store this cameras using storedCameras array. In cameras array there are 5 cameras.

I added a flag allCameras to change between the stored cameras mode and all cameras mode.

And I'm using the G key to switch between the cameras either the stored or the all cameras.

But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera. And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag.

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

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;
    public bool allCameras = false;
    private Camera[] storedCameras;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    void Start()
    {
        storedCameras = cameras;

        if (allCameras == true)
        {
            cameras = new Camera[Camera.allCameras.Length];
            cameras = Camera.allCameras;
        }

        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (allCameras == true)
        {
            cameras = new Camera[Camera.allCameras.Length];
            cameras = Camera.allCameras;
        }
        else
        {
            cameras = new Camera[storedCameras.Length];
            cameras = storedCameras;
        }

        if (Input.GetKeyDown(KeyCode.G))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;
            currentCameraOriginalPosition = originalPosition[currentCamera];
        }

        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }
}

```

# Answer
> 2 votes
Calling `Camera.allCameras` returns only the enabled cameras in your scene. Since you disable cameras you're not using, that means you have fewer to choose from the next time you query it.

Instead, you can cache a private list of `_allCameras` in `Start()`, provided all your cameras are enabled at the time the scene loads, and you're not spawning more or deleting them dynamically over time.

You also only need to swap your lists when you're actually performing a camera swap, rather than every frame.

```
public bool cycleAllCameras = false;
public Camera[] storedCameras;

Vector3[] _originalPositions;
Vector3[] _lastPositions;
Camera[] _currentCameraSequence;
Camera[] _allCameras;
int _currentCameraIndexInCycle;
int _currentCameraIndexInAll;

// Rather than store the current camera's index, AND its reference,
// AND its name, AND its position, AND its original position...
// let's just store its index, and everything else can be inferred
// from that, so we don't have redundant data that can go out of sync.
public Camera currentCamera {
    get {
        return _currentCameraSequence[_currentCameraIndexInCycle];
    }
}

void Start() {
   // Cache all cameras enabled at the start of the scene;
   _allCameras = Camera.allCameras;
   _originalPositions = new Vector3[_allCameras.Length];
   _lastPositions = new Vector3[_allCameras.Length];

   // Select the first camera in whichever list we're using
   _currentCameraSequence = cycleAllCameras ? _allCameras : storedCameras;
   Camera currentCamera = this.currentCamera;

   // Disable every camera except the one we're using,
   // and cache their original positions to use later.
   for(int i = 0; i < _allCameras.Length; i++) {
       _allCameras[i].enabled = (_allCameras[i] == currentCamera);
       _lastPositions[i] = _originalPositions[i] = _allCameras[i].transform.position;
   }
}

void LateUpdate() {
    // Update the current camera's last position,
    // before we switch from it to a dormant one.
    _lastPosition[_currentCameraIndexInAll] = currentCamera.transform.position;

    // Use a named input so the user can remap it.
    if(Input.GetButtonDown("CycleCamera"))
        CycleCamera();
}

// Cycle action is in its own public method, in case you
// want to trigger it from other scripts or UI buttons.
public void CycleCamera() {
    currentCamera.enabled = false;

    // If we've swapped sequences, re-index the camera.
    if(_currentCameraSequence == storedCameras) {
        if(cycleAllCameras == true) {
              _currentCameraIndexInCycle = _currentCameraIndexInAll;
              _currentCameraSequence = _allCameras;
        }
    } else if(cycleAllCameras == false) {
        _currentCameraIndexInCycle = Mathf.Max(0, System.Array.IndexOf(storedCameras, currentCamera));
        _currentCameraSequence = storedCameras;
    }

    // Step to the next camera, and wrap around the sequence.
    _currentCameraIndexInCycle = (_currentCameraIndex + 1) % _currentCameraSequence.Length;

    // Ensure we have a valid index into the "all" list
    // for looking up original position / last position / etc.
    _currentCameraIndexInAll = System.Array.IndexOf(_allCameras, currentCamera);

    //
    currentCamera.enabled = true;
}

```

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


# Question
Title: Dynamically Changing GameObject makes NullReferenceException(C# Unity)
Here's my code

```
[SerializeField]
GameObject FogEffect = null;

void Update()
{
    GetFogs();
}

void GetFogs()
{
    int env_idx = tzPlayInfo.Instance.ENV_01_IDX;
    //0: day, 1: night
    if (env_idx == 0 && FogEffect == null)
    {
        FogEffect = transform.Find("GO Root/day/01_Env_Lev01_test01/Fog01 (1)").gameObject;
    } else if (env_idx == 1 && FogEffect == null)
    {
        FogEffect = transform.Find("GO Root/night/01_Env_Lev01_night-test02/Fog01").gameObject;
    } else
    {
        Debug.Log("There's something wrong!");
    }
}

```

I'm changing my prefabs dynamically so when it is **Evening** I am using evening prefab then if it is **Day** I'm using my day prefab. So basically i need to do it on `Update()` function because I am making an Option that the user can `enable` and `disable` the *FOG* GameObject. Now my problem is that everytime it changes the environment **(Day and Night)** a

> NullReferenceException

is popping out but after that it will get the *Fog* GameObject again.

How can I solve this error.

EDITTED: Here's the whole code for my **OptionSetting.cs**

```
using System;

```

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.ImageEffects; using System.Linq;

public class MC\_SettingBehaviour : MonoBehaviour {

```
[SerializeField]
GameObject[] CameraEffectComponents = new GameObject[43];

bool foundAllComponents = false;

[SerializeField]
GameObject FogEffectMorning = null;

[SerializeField]
GameObject FogEffectEvening = null;
bool fog = false;

private void Start()
{
    if (PlayerPrefs.GetInt(OptionPopup.LiveStreaming_) == 1)
    {
        this.enabled = false;
    } else
    {
        StartCoroutine(CameraComponents());
    }
}

void Update()
{
    if (!fog)
    {
        GetFogs();
        Debug.Log("BOOLEAN FOG :" + fog);
    }

    //if the camera components are all found
    if (foundAllComponents)
    {
        //Camera Option
        OptionCameraOnAndOff();
    }
    else
    {
        Debug.Log("Couldn't find yet any components on camera please wait...");
    }
}

IEnumerator CameraComponents()
{

    CameraEffectComponents[0] = transform.Find("GO Root/Camera/AIR_1(Clone)/GameObject/Camera").gameObject;
    CameraEffectComponents[1] = transform.Find("GO Root/Camera/AIR_2(Clone)/Camera").gameObject;
    CameraEffectComponents[2] = transform.Find("GO Root/Camera/Paddock_1(Clone)/CameraPos/GameObject/Camera").gameObject;
    CameraEffectComponents[3] = transform.Find("GO Root/Camera/TV_1_lead(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[4] = transform.Find("GO Root/Camera/TV_2_far(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[5] = transform.Find("GO Root/Camera/TV_2_lead(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[6] = transform.Find("GO Root/Camera/LAST_SPURT_1(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[7] = transform.Find("GO Root/Camera/Test30(Clone)/Poss/Camera").gameObject;

    CameraEffectComponents[8] = transform.Find("GO Root/Camera/Test01(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[9] = transform.Find("GO Root/Camera/Test02(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[10] = transform.Find("GO Root/Camera/Test03(Clone)/Poss/Camera").gameObject;

    CameraEffectComponents[11] = transform.Find("GO Root/Camera/Test04(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[12] = transform.Find("GO Root/Camera/Test05(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[13] = transform.Find("GO Root/Camera/Test06(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[14] = transform.Find("GO Root/Camera/Test07(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[15] = transform.Find("GO Root/Camera/Test08(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[16] = transform.Find("GO Root/Camera/Test09(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[17] = transform.Find("GO Root/Camera/Test10(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[18] = transform.Find("GO Root/Camera/Test11(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[19] = transform.Find("GO Root/Camera/Test12(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[20] = transform.Find("GO Root/Camera/Test13(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[21] = transform.Find("GO Root/Camera/Test14(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[22] = transform.Find("GO Root/Camera/Test15(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[23] = transform.Find("GO Root/Camera/Test16(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[24] = transform.Find("GO Root/Camera/Test17(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[25] = transform.Find("GO Root/Camera/Test18(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[26] = transform.Find("GO Root/Camera/Test19(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[27] = transform.Find("GO Root/Camera/Test20(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[28] = transform.Find("GO Root/Camera/Test21(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[29] = transform.Find("GO Root/Camera/Test22(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[30] = transform.Find("GO Root/Camera/Test23(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[31] = transform.Find("GO Root/Camera/Test24(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[32] = transform.Find("GO Root/Camera/Test25(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[33] = transform.Find("GO Root/Camera/Test26(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[34] = transform.Find("GO Root/Camera/Test27(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[34] = transform.Find("GO Root/Camera/Test28(Clone)/Poss/Camera").gameObject;
    CameraEffectComponents[35] = transform.Find("GO Root/Camera/Test29(Clone)/Poss/Camera").gameObject;

    CameraEffectComponents[36] = transform.Find("GO Root/Camera/HORSE_JOCKEY(Clone)").gameObject;

    CameraEffectComponents[37] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_1(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[38] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_2(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[39] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/TOP_3(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[40] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/FRONT_1(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[41] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/SIDE_1(Clone)/Pos/Camera").gameObject;
    CameraEffectComponents[42] = transform.Find("GO Root/CommonEnv/follow_camera's_focus/SIDE_2(Clone)/Pos/Camera").gameObject;

    //lets use a lambada expression here for declaring a null
    if (CameraEffectComponents.Any(e => e != null))
    {
        foundAllComponents = true;
    } else
    {
        foundAllComponents = false;
    }
    yield return null;
}

void GetFogs()
{
    int env_idx = tzPlayInfo.Instance.ENV_01_IDX;
    //0: day, 1: night
    try
    {
        if (env_idx == 0 && FogEffectMorning == null)
        {
            fog = false;
            FogEffectMorning = transform.Find("GO Root/day/01_Env_Lev01_test01/Fog01 (1)").gameObject;
            Debug.Log("Its morning must get the Fog Morning Effect");
            //Fog Option

            OptionFogMorningOnAndOff();
            fog = true;
        }
        else if (env_idx == 1 && FogEffectEvening == null)
        {
            fog = false;
            FogEffectEvening = transform.Find("GO Root/night/01_Env_Lev01_night-test02/Fog01").gameObject;
            Debug.Log("Its morning must get the Night Morning Effect");
            //Fog Option

            OptionFogEveningOnAndOff();
            fog = true;
        }
        else
        {
            Debug.Log("There's something wrong!");
        }
    }
    catch (Exception e)
    {
        Debug.Log("Opps something is wrong :" + e.ToString());
    }

}

void OptionCameraOnAndOff()
{
    foreach (GameObject cam in CameraEffectComponents)
    {
        if (PlayerPrefs.GetInt(OptionPopup.CameraOptionSaving) == 1)
        {
            if (cam.GetComponent<Bloom>() != null)
            {
                cam.GetComponent<Bloom>().enabled = true;
            }

            if (cam.GetComponent<DepthOfFieldDeprecated>() != null)
            {
                cam.GetComponent<DepthOfFieldDeprecated>().enabled = true;
            }

            if (cam.GetComponent<DepthOfField>() != null)
            {
                cam.GetComponent<DepthOfField>().enabled = true;
            }

        }
        else
        {

            if (cam.GetComponent<Bloom>() != null)
            {
                cam.GetComponent<Bloom>().enabled = false;
            }

            if (cam.GetComponent<DepthOfFieldDeprecated>() != null)
            {
                cam.GetComponent<DepthOfFieldDeprecated>().enabled = false;
            }

            if (cam.GetComponent<DepthOfField>() != null)
            {
                cam.GetComponent<DepthOfField>().enabled = false;
            }
        }
    }
}

void OptionFogMorningOnAndOff()
{
    try
    {
        if (PlayerPrefs.GetInt(OptionPopup.FogOptionSaving) == 1)
        {
            FogEffectMorning.SetActive(true);
        }
        else
        {
            FogEffectMorning.SetActive(false);
        }

    }
    catch (Exception e)
    {
        Debug.Log("Something is wrong here :" + e.ToString());
    }

}

void OptionFogEveningOnAndOff()
{
    try
    {
        if (PlayerPrefs.GetInt(OptionPopup.FogOptionSaving) == 1)
        {
            FogEffectEvening.SetActive(true);
        }
        else
        {
            FogEffectEvening.SetActive(false);
        }

    }
    catch (Exception e)
    {
        Debug.Log("Something is wrong here :" + e.ToString());
    }
}
}

```

# Answer
I couldn't do it on the Find method so basically what i did is make a script on the fog(evening) fog(morning) and put this script so that they can be still disabled and enabled .

```
void Update ()
{
    if (PlayerPrefs.GetInt(OptionPopup.FogOptionSaving) == 1)
    {
        this.GetComponent<MeshRenderer>().enabled = true;
    }
    else
    {
        this.GetComponent<MeshRenderer>().enabled = false;
    }
}

```

I just turn on and off the mesh renderer. Hahaha thanks guys
> 0 votes

---
Tags: unity, c#, android, unityscript
---


# Question
Title: How does Actionscript choose which order to run objects' code in?
I can only assume that Flash runs code in the order that objects were created - so newer objects are run later. Is this true?

Is there any way, other than deleting and recreating objects, that I can change this order?

# Answer
If your are working on Flash or Adobe Animate area, change the depth of your MovieClips to change the order of running them by select and press ctrl+shift+(UP or DOWN).
> 1 votes

---
Tags: flash, actionscript-3, gameobject
---


# Question
Title: Character jumping but not returning to ground platform game AS3
I am making a platform game where the main character moves right and left and jumps however my character jumps and does not return to the ground but stays on top of the stage.My characters movie-clip symbol is called 'naruto' and my ground symbol is called 'ground'.

Here is my code:

```
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;

naruto.gotoAndStop("stance");
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var narutoSpeed:Number = 10;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME,gameLoop);

function keyDownHandler(keyEvent:KeyboardEvent):void
{
    if (keyEvent.keyCode == Keyboard.RIGHT)
    {
    rightPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
    leftPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
    upPressed = true;
    }else if(keyEvent.keyCode == Keyboard.DOWN)
    {
    downPressed = true;
    }

}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
    if (keyEvent.keyCode == Keyboard.RIGHT)
    {
    rightPressed = false;
        naruto.gotoAndStop("standright")
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
    leftPressed = false;
    naruto.gotoAndStop("standleft")
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
    upPressed = false;
    naruto.gotoAndStop("stance")
    }else if(keyEvent.keyCode == Keyboard.DOWN)
    {
    downPressed = false;
    naruto.gotoAndStop("stance")
    }

}

function gameLoop(loopEvent: Event): void {
    //If the right key is pressed, and the left key is NOT pressed
    if (rightPressed && !leftPressed) {
        naruto.x += narutoSpeed;
        naruto.gotoAndStop("right");
    }

    if(leftPressed && !rightPressed) {
        naruto.x -= narutoSpeed;
        naruto.gotoAndStop("left");

    }
var jumpHeight =0;
var defaultJumpSpeed = 20;
var jumpSpeed = 20;

if(upPressed && naruto.hitTestObject(ground))
{
    trace("HELLO!");
naruto.y -= jumpSpeed;
jumpSpeed-= 4;
}

if(upPressed)
{
    trace("HELLO!");
jumpHeight++;
naruto.y -= jumpSpeed;
if(jumpHeight>10)
jumpSpeed -= 4;
}

if(naruto.hitTestObject(ground))
{
    trace("HELLO!");
jumpHeight =0;
jumpSpeed = defaultJumpSpeed;
}
    }

```

Here is the link for my work: https://www.mediafire.com/?8d5opy49fuqmup5

Here is the problem:

# Answer
You forgot to add Newton's listens about gravity here :D. change the function gameLoop with mine and add tree variable out of it.

```
const defaultJumpSpeed = 20;
const gravity:Number = 2 ;
var jumpSpeed = 0;

function gameLoop(loopEvent: Event): void {
    //If the right key is pressed, and the left key is NOT pressed
    if (rightPressed && !leftPressed) {
        naruto.x += narutoSpeed;
        naruto.gotoAndStop("right");
    }

    if(leftPressed && !rightPressed) {
        naruto.x -= narutoSpeed;
        naruto.gotoAndStop("left");

    }

//New lines by ME
    if(naruto.hitTestObject(ground))
    {
        //The naruto is on the ground
        if(upPressed)
        {
            //The jump button pressing. you may need to prevent these lines to call more than one later
            trace("HELLO!");
            jumpSpeed = defaultJumpSpeed;
            naruto.y -= jumpSpeed ;
        }
        else
        {
            //The naruto is not jumping. stop his falling
            jumpSpeed = 0 ;
        }
    }
    else
    {
        //naruto is falling down, may be he was jumped or he felled to the hole.
        naruto.y -= jumpSpeed ;
        jumpSpeed -= gravity ;
        jumpSpeed = Math.min(jumpSpeed,-defaultJumpSpeed);// To prevent him from burning like Meteorite because of it's speed
    }
}

```

After that you need to change the const variable of defauldJumbSpeed and gravity power to change the jump height.

Good luck
> 1 votes

---
Tags: game-mechanics, flash, actionscript-3, game-loop
---


title: flash - hitTestObject() mafunction?

text:
# Question
Title: flash - hitTestObject() mafunction?
Is there a way that even though two objects that have different `y` co-ordinate collide?
In my game, I wanted to make my object rotate as explained in previousquestion. When I added the code, the object now dissapears from the scene even though it's `x` and `y` co-ordinate are in the scene. I `traced`(in the function that kills the characer if it touches it. i.e `hitt`) the `x` and `y` value of the object and found that it is still there on the scene.
The code is:

```
ground.addEventListener(Event.ENTER_FRAME, hitt);

function hitt(event: Event) {
    if (green.hitTestObject(ground) || blue.hitTestObject(ground) || brown.hitTestObject(ground) || black.hitTestObject(ground)) {
        dead = true;
    }
    else if (kill.hitTestObject(black) || kill.hitTestObject(green) || kill.hitTestObject(blue) || kill.hitTestObject(brown)) {
        dead = true;
        trace("here",kill.y,green.y,green.x);
    }
}

```

The output is:

```
[SWF] hello.swf - 519178 bytes after decompression
here -608.95 -401 62.55

```

I don't know what's going on? Please Help..!!

# Answer
The hitTestObject is not accurate at all. it will creates a rectangle from your both movieClips and then it will calculate the collision for those rectangle witch may be the parts of empty spaces of your movieClip.

you have to accurate your collision control by using hitTestPoint that detect hitTest between a rectangle of first area ( and that should be your bigger MovieClip ) and the point that you need to check for collision:

```
kill.hitTestPoint(black.x,black.y,true);//Find some sample for better understanding

```

Or for the best collision detection, you need to use hitTest of BitmapDatas. that will control the collision pixel by pixel. but its a little complicated.

see this : https://stackoverflow.com/questions/48906389/actionscript-3-alternatives-to-hittestobject-or-position-constraints/48956262#48956262
> 0 votes

---
Tags: flash, actionscript
---


# Question
Title: Why some audio files are not working in Unity?
I am making a 2D game in which I wanted to attach audio file to a button. I was able to do this successfully. But later I felt like changing that sound. So I simply replaced it with another audio file. Then it stopped working! When I again attached the first audio file instead of second one, it worked again.

My setup is as follows: The file format is wav. I created an empty gameobject and attached an Audio Source component to it. Assigned an audio clip to it. Unchecked "Play on Awake". Went to the OnClick() section of the UI Button. Clicked the plus sign to add an item to the list. Assigned the Audio Source object to the object field. Chose AudioSource.Play in the dropdown.

I wanted to know why is my second audio file of the same format not working!

# Answer
I got my issue resolved. The actual problem was that, when I click on the UI button, another scene loads. And when this happens, the audio which was supposed to be played while I click the button, gets cut off! Therefore, only those audios which are very very short in length would be heard. This is the reason why the second audio was not heard. In order to fix this, put the AudioSource on a game object with a script that contains this:

```
DontDestroyOnLoad( gameObject );

```

http://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

Thanks a lot to everyone who tried to help me!!
> 1 votes

---
Tags: unity, audio
---


# Question
Title: AudioSource NullReferenceException: Object reference not set to an instance of an object
I honestly don't understand what's going on. This was working perfectly fine yesterday. I have a GameObject in my scene that has an AudioSource attached. The AudioSource has a dragged in .wav file in it's AudioClip section. The GameObject also has a script attached. The script looks like:

```
using UnityEngine;
using System.IO;

public class MyData : MonoBehaviour {
    AudioSource audio;

    // Use this for initialization
    void Start () {
        audio = GetComponent<AudioSource>();
    }

    void Update() {
        if (audio.isPlaying) { /* stuff */ }
    }
}

```

The script compiles file, the audio plays fine, I've quadruple checked everything, but I keep getting the error "NullReferenceException: Object reference not set to an instance of an object" at the audio.isPlaying line.

# Answer
> 1 votes
Consider slapping a

```
[RequireComponent(typeof(AudioSource))]

```

attribute above this class definition, so that it's harder to accidentally end up with it on an object with no `AudioSource` to find with `GetComponent`.

When you add the script in the Inspector, it will automatically add an AudioSource if it's absent. And when you try to delete the AudioSource, it will warn you that another script is depending on it.

It won't do anything to help with existing objects in your scene/assets folders that were already misconfigured before adding this attribute though. For those, the debugging steps Hellium recommended are likely your best bet.

It also won't catch components deleted at runtime, but those generally fire a `MissingReferenceException` rather than a `NullReferenceException`, so I don't think that's the issue you're facing here.

---
Tags: unity
---


# Question
Title: EnemyAI rotating on Y-axis in opposite direction
After a battle flag has gone off and the player has entered an enemy's battle zone I want to keep track of the player when it moves and make sure the enemy's Z-axis is always pointing towards the player.

Upon the player entering the battle zone, the enemy automatically marks the player as its target However there is a chance that the Z-axis may not be pointing towards the enemy's target when the battle is first initiated. I decided to shoot a ray cast from the Z-axis of the enemy when the battle flag goes off and rotate the enemy until the ray and the player intersect thus telling me that enemy's Z-Axis is lined up correctly.

the enemy always has a reference to its current target. My idea was that as once the enemy spots its target initially, it can save the position of the most recent spotting and then take the delta of the CurrentTargetPosition.x and the LastSpottingPosition.x If the delta is positive rotate right and if the delta is negative rotate left.

THE ISSUE: my math or logic must be flawed somewhere because although it works sometimes, other times the enemy will randomly rotate itself in the opposite direction and the ray cast will essentially take the long route to hit the player instead of the shortest route as intended. Also the Local Origin of the enemy and the player are at different height respectively but I dont think that should matter in my case Code Below.

```
//create ray from enemy position orgin and point it on the Z-Axis
        Ray ray = new Ray(CurrentEnemyTransform.position, CurrentEnemyTransform.forward);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 50f))
        {
            Debug.DrawLine(ray.origin, hit.point);

            //ray hits current enemy target
            if (hit.transform == CurrentTargetTransform)
            {
                //check if enemy has seen its target before while in this battle
                //or is it the first time
                if (enemy.hasTargetLastPosition)
                    //replace old last seen position with most recent spotting
                    enemy.ReplaceTargetLastPosition(hit.transform.position);
                //or add the first spotting of target while in this battle
                else enemy.AddTargetLastPosition(hit.transform.position);
            }
            //ray is not intersectiing with the enemy's current target so rotate to look for it
            if (hit.transform != CurrentTargetTransform)
            {
                //check if enemy has seen its target once before in battle
                if (enemy.hasTargetLastPosition)
                {
                    //since last spotting has my target moved more to the left or right?
                    if (enemy.targetLastPosition.value.x > CurrentTargetTransform.position.x)
                    {
                        //rotate right
                        CurrentEnemyTransform.Rotate(-Vector3.up, 5f, Space.Self);
                    }
                            //rotate left
                    else CurrentEnemyTransform.Rotate(Vector3.up, 5f, Space.Self);
                }
                //never seen target yet during this battle so default rotation to right till you found it
                else CurrentEnemyTransform.Rotate(-Vector3.up, 5f, Space.Self);
            }

```

# Answer
```
if (enemy.targetLastPosition.value.x > CurrentTargetTransform.position.x)

```

does not tell you which direction to rotate in. You are just determining whether the player has moved left or right. You need the difference between the angles of the vectors formed between the target and the enemy at the current and last position.

Imagine the following scenarios where E is the enemy and T is target:

```
    T

E

```

If T moves in the positive x direction, then E must rotate clockwise.

and

```
E

    T

```

If T moves in the positive x direction, then E must rotate counterclockwise.

So you can see that dx is not always the same sign as dtheta.

EDIT:

```
vector1 = CurrentEnemyTransform.forward;
vector2 = normalize(targetPos - enemyPos);

```

Then you need to rotate from vector1 to vector2 in 3d space. I'm not an expert at Unity, but I believe it works like this...

```
[get quaternions for vector 1 and 2]

dq = Quaternion.rotateTowards(quat1, quat2, dTheta);

CurrentEnemyTransform.forward = dq * CurrentEnemyTransform.forward;

```
> 1 votes

---
Tags: unity, c#, collision-detection, physics, mathematics
---


title: Detect android device rotation

text:
# Question
Title: Detect android device rotation
I am developing a game in android and I want to be able to use device rotation for moving. So, I am not sure what sensors should I use. I tried gyroscope, it will do, but there are not a lot of devices that supports gyroscope sensors. So, I want to use rotation around x,y,z axis not change like landscape/portrait mode. What sensors would be the best? I already tried to google it but I couldn't find anything.

# Answer
Use the rotation vector sensor. This combines the gyroscope, compass and acceleration sensors and outputs a vector pointing in the same direction as the phone.
> 0 votes

---
Tags: android, android-studio
---


# Question
Title: Is there any way to change the layering of objects in Actionscript 3 without altering the run order?
I'm making a simple platformer in Adobe Animate, and I need the player to be layered in front of the stage because of a gimmick in the game. Unfortunately, whenever I change the layering order, it also seems to change the order that AS3 runs the instances.

Is there any way to change the layering order without affecting the instance order, or vice-versa?

I'm only just starting with programming, so please bear in mind that I probably won't understand many of the technical terms.

Thanks in advance!

# Answer
> 1 votes
When you say "runs the instances" what logic specifically are you talking about?

*You* should not be processing game logic by looping over `DisplayObject.children`. That array is primarily for the *display system* to use. *You* should keep your own, separate `Vector` containing the instances you want, and run them in your own order, whatever that may be (e.g. sort them first).

# Answer
> 0 votes
Whenever you need to bring something to the top layer, you can call the `this.addChild(player_mc)` again. that make it come back to the top.

I hope that it has been help full.

---
Tags: actionscript-3, instancing, layers
---


# Question
Title: Camera and enemy behaviour in AS3 platformer
beginner in AS3 here. I am working on a platformer game based on the code of a provided example exercise. I have the following problem:

* I have an enemy who shoots bullets. The enemy is the parent, and the bullet are the child. When I move to the next scene (level), the bullets are still there, but invisible, even using the removeEventListener to shut down the bullet hit check.

Here is the code of the child "disparoEnemigo\_mov":

```
addEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
function fl_MoveEnemyShot(event: Event) {
try {
    if (enemy_shot.y < 300) {
        if (enemy_shot.hitTestObject(Object(this.parent).mario)) {

            variablesGlobales.variables().vidas -= 1;
            Object(root).texto.text =
variablesGlobales.variables().vidas.toString();
            trace("vidas: " + variablesGlobales.variables().vidas);
            if (variablesGlobales.variables().vidas < 1) {
                MovieClip(this.parent).gotoAndStop(2);
            }
            this.parent.removeChild(this);
            removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
        } else {
            enemy_shot.y += 3;
        }
    } else {
        trace("LLEGADA");
        removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
        this.parent.removeChild(this);
    }
} catch (error: Error) {
    removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
}
}

import flash.events.Event;
import flash.media.SoundMixer;

addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);

function fl_EnterFrameHandler(event: Event): void {
try{
if (this.hitTestObject(Object(this.parent).mario)) {

    SoundMixer.stopAll();
    var sound:gameOver = new gameOver();
    sound.play();
    Object(this.parent).mario.y=1000;
    Object(this.parent).mario.x-=15;
    trace("Mario dies");
    var cartel:StageLose = new StageLose();
    stage.addChild(cartel);
    cartel.x = -85;
    Object(this.parent).mario.y = 1000;
    }
}catch(error: Error){
removeEventListener (Event.ENTER_FRAME, fl_EnterFrameHandler);
}
}

```

And this is the code of the parent, "enemigo\_mov":

```
var leftPressed: Boolean = true;
var rightPressed: Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, fl_MoveEnemy);
function fl_MoveEnemy(event: Event) {
try{
if (leftPressed) {
    enemy1.x -= 0;
    if (enemy1.x < -120) {
        leftPressed = false;
        rightPressed = true;
    }
} else if (rightPressed) {
    enemy1.x += 1;
    if (enemy1.x > 120) {
        rightPressed = false;
        leftPressed = true;
    }
}
var number: Number = Math.random();
if (number < 0.05){// &&
variablesGlobales.variables().coleccionEnemigos.indexOf(this) != -1) {
    trace("creation");
    var disparo: disparoEnemigo_mov = new disparoEnemigo_mov();
    this.parent.addChild(disparo);
    disparo.x=enemy1.x +115;
    disparo.y=enemy1.y +115;

    //disparo.z=50;
    trace(disparo.x + " " + disparo.y);
    }

}catch(error:Error){
removeEventListener(Event.ENTER_FRAME, fl_MoveEnemy);
}
}

```

In both codes, "mario" is the player character.

What I need to do is to stop the bullet creation of ""disparoEnemigo\_mov" when we move to the next scene. Shouldn't the "removeEventListener(Event.ENTER\_FRAME, fl\_MoveEnemy)" line stop the bullets to check if there is any collision with the player?

Any help or resource will be helpful. Thank you so much!

# Answer
> 1 votes
It has been a while since I used AS3, but...

I believe you are expanding the hitbox of the enemy by adding bullets as children. Even when the bullets are removed from the enemy, the hitbox stays artificially expanded.

For this reason... I don't recommend adding bullets as children. Create the bullets on the same layer and keep the handle, so you can hittest them and delete them individually.

# Answer
> 0 votes
You're adding the bullet with `this.parent.addChild(disparo);` but you are not removing it when your hit event fires.

For your specific case, you would remove it after `Object(this.parent).mario.y = 1000;` with `Object(this.parent).removeChild(this);`

# Answer
> 0 votes
The bullet should be very small, so it's better to use hitTestPoint instead o hitTest. it is more accurate than hitTest.

See this tutorial: http://www.ilike2flash.com/2009/08/collision-detection-in-actionscript-3.html

---
Tags: flash, actionscript-3, platformer
---


# Question
Title: Cube changes position when I use a script to change its UV mapping
I try to code a Minecraft like game with Unity 2017.3. I found a C# script for creating a UV mapped cube with the following layout, using my own texture with 64x64 pixel sides:

If I run the game my cube is now placed in the air. How do I control its position?

Here is the script I'm using:

```
using UnityEngine;
using System.Collections;

[RequireComponent(typeof (MeshFilter))]
[RequireComponent(typeof (MeshRenderer))]
public class UVMapping : MonoBehaviour {

    void Start () {

        float size = 1f;

        Vector3[] vertices = {
            new Vector3(0, size, 0),
            new Vector3(0, 0, 0),
            new Vector3(size, size, 0),
            new Vector3(size, 0, 0),
            new Vector3(0, 0, size),
            new Vector3(size, 0, size),
            new Vector3(0, size, size),
            new Vector3(size, size, size),
            new Vector3(0, size, 0),
            new Vector3(size, size, 0),
            new Vector3(0, size, 0),
            new Vector3(0, size, size),
            new Vector3(size, size, 0),
            new Vector3(size, size, size),
        };

        int[] triangles = {
            0, 2, 1, // front
            1, 2, 3,
            4, 5, 6, // back
            5, 7, 6,
            6, 7, 8, //top
            7, 9 ,8,
            1, 3, 4, //bottom
            3, 5, 4,
            1, 11,10,// left
            1, 4, 11,
            3, 12, 5,//right
            5, 12, 13
        };

        Vector2[] uvs = {
            new Vector2(0, 0.66f),
            new Vector2(0.25f, 0.66f),
            new Vector2(0, 0.33f),
            new Vector2(0.25f, 0.33f),
            new Vector2(0.5f, 0.66f),
            new Vector2(0.5f, 0.33f),
            new Vector2(0.75f, 0.66f),
            new Vector2(0.75f, 0.33f),
            new Vector2(1, 0.66f),
            new Vector2(1, 0.33f),
            new Vector2(0.25f, 1),
            new Vector2(0.5f, 1),
            new Vector2(0.25f, 0),
            new Vector2(0.5f, 0),
        };

        Mesh mesh = GetComponent<MeshFilter> ().mesh;
        mesh.Clear ();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.Optimize (); // this is deprecated
        mesh.RecalculateNormals ();
    }
}

```

# Answer
The default Unity cube mesh has its center at the object's pivot ((0, 0, 0) in local space), and extends to `-0.5` and `+0.5` on each axis.

The script you're using creates a new cube-shaped mesh with one corner at the pivot, extending from `0` to `size` on each axis.

So if you're using it to replace a default Unity cube at runtime, you'll find it's shifted by 0.5 units.

You can fix this by adding a quick fixup after your vertices block:

```
for(int i = 0; i < vertices.Length; i++)
    vertices[i] -= Vector3.one * 0.5f * size;

```

Or you can go through each line and replace every `size` by `0.5f * size`,
and every `0` by `-0.5f * size` (defining an `extents = 0.5f * size` makes this neater)

One last note: each cube you use this script on will create its own copy of the mesh, eating memory and draw calls unnecessarily. You might want to consider grouping these, so that you calculate the mesh only once and share it among many cubes. Or even better, just make the mesh you want offline and import it as an asset that all your cubes can reference.
> 0 votes

---
Tags: unity, uv-mapping
---


title: Omnidirectional Faded Soft Shadows

text:
# Question
Title: Omnidirectional Faded Soft Shadows
I'm doing research to implement a shadow algorithm for omnidirectional soft shadows in a real-time 3D renderer. I've read about PCF but to me it doesn't look very realistic since it doesn't "fade" with the distance to the blocker like PCSS would.

The problem is PCSS uses the penumbra radius to simulate the "fade" effect which omnidirectional lights don't create. Therefore, only lights that do produce a penumbra (like area lights) are natively supported by the algorithm.

So I'll break this question into 2:

1. Can I still use PCSS on omnidirectional lights by "cheating" and applying a tweaked constant value as the light area parameter?
2. Is there another algorithm that produces this "fade" effect and does work with omnidirectional lights?

# Answer
A mathematically perfect point light that shines in exactly straight rays doesn't cast soft shadows.

Imagine you're a tiny bug crawling along the shadow-receiving surface. From each spot you crawl to, you can either see the point light (and your eye is fully illuminated by it), or you can't (and your eye is fully shadowed).

The light source doesn't have any thickness for it to be partly occluded, or shining at partial strength. That leaves its shadows hard as can be, if we're following the mathematical model strictly (ie. not imitating atmospheric or diffraction effects that could bend a fraction of the light into non-straight rays)

So by setting out to render soft shadows, you're already implicitly stating "I'm going to treat this light like it has some area" so that some spots on the shadow receiver see 50% of the light, and get illuminated to 50% brightness, for instance.

So this:

> Can I still use PCSS on omnidirectional lights by "cheating" and applying a tweaked constant value as the light area parameter?

sounds like a valid way to implement that intention.
> 1 votes

---
Tags: graphics, lighting, shadows, shadow-mapping, realtime
---


# Question
Title: How to Calculate Caridnal Direction from Unit Vector
I have unit Vector of acceleration in local space of object. Now I want to calculate Cardinal Direction from (North, East, South, West).

So Far I tried to:

```
FQuat QRot = LocalAcceleration.ToOrientationQuat();
    FRotator Rot = FRotator(QRot);
    float Angle = Rot.Yaw;
    float Angle2 = (FMath::RoundToInt(Angle) + 360) % 360;

```

(Another version was calulcating atan2).

Then:

```
if (FMath::IsWithin(IntAngle, 0, 46)
    && FMath::IsWithin(IntAngle, 314, 0))
{
    NewDir = EFourCardinalDirection::N;
}
if (FMath::IsWithin(IntAngle, 134, 228))
{
    NewDir = EFourCardinalDirection::S;
}
if (FMath::IsWithin(IntAngle, 46, 136))
{
    NewDir = EFourCardinalDirection::E;
}
if (FMath::IsWithin(IntAngle, 229, 313))
{
    NewDir = EFourCardinalDirection::W;
}

```

I also tried to calculate eighth directions and then just assign the four based on the previous eight.

Neither way provided stable results. There are some jumps between directions depending on object movement.

# Answer
Here is solution:

```
float Atan2Angle = FMath::Atan2(LocalVelocity.Y, LocalVelocity.X);
int32 Dir = FMath::RoundToInt((Atan2Angle * 2 / PI) + 4) % 4;

```

LocalVelocity - Unit vector of character velocity In local space.
> 0 votes

---
Tags: mathematics, vector, linear-algebra, direction
---


title: Drawing & transforming matrices upwards

text:
# Question
Title: Drawing & transforming matrices upwards
I'm drawing a hierarchy of 3D objects in C# XNA where each objects has a transform that holds position, rotation and scale.

I get my expected results If I draw my objects from my root node in this fashion:

```
public void Draw(Matrix world, Matrix view, Matrix proj)
{
    foreach (var item in Children)
        item.Draw(world * item.Transform, view, proj);
}

```

However, **I want to draw my objects by starting with a child node, drawing upwards**, and achieving drawing from a **child-object relative space**. How would I do this?

I've tried a number of ways or drawing the parent nodes with inverted transform, but I'm not getting the correct results, I'm guessing I need to take care of the multiplication order, but I don't know what that is if I'm going up instead of down.

# Answer
> 1 votes
Having done a system exactly like this. It's basically am ordering issue as you seem to have most of the pieces in place. The part you need to do though is understand their is another multiplication you need to do and that's the attachment point.

Will do this as a basic step process for now.

1. Create a world transform for model x. Scale rotate translate.
2. In local model space. Create a matrix translation for your attachment point for your child object. Multiply this with your x transform to get where your child would be in world space.
3. Create a scale rotate transform for the model in ITS local space. Should be the identity matrix most likely. But if its a tank turret then its the rotarion matrix.
4. Multiply child model matrix by the attachment matrix.
5. Repeat 3 and 4 for every subsequent child.

The use of this technique is not limited to the model rendering but also for things such as particle attachment points and barrel ejection points on guns etc.

Link to example -\>

You can reference the game here. There is a tank that has articulated turrets, Anti aircraft battery that rotates on its base, and planes with articulated propellers. The bullet ejection points are accurate and as depicted in screenshot below.

# Answer
> 0 votes
The "simple Animation Sample" that MS offered in their educational site for XNA demonstrates how that is done. http://xbox.create.msdn.com/en-US/education/catalog/sample/simple\_animation

It uses a tank model but basically the tank's hatch and gun barrel are children of the turret which is a child of the tank body and it shows how to move the children while moving or not moving the parents.

A big part of that is the `Model.CopyAbsoluteBoneTransformsTo()` method

---
Tags: c#, xna, mathematics, vector, matrix
---


title: SFML GetRenderWindow Method Help

text:
# Question
Title: SFML GetRenderWindow Method Help
I have been following the "SFML Game Development By Example" and on chapter 2, the book was showing the example game design of a *Snake* game. However he didn't write the code of some header classes and didn't mention whether they should exist. I tried writing some of them but encountered an error:

```
sf::RenderWindow* Window::GetRenderWindow(return &m_window;)

```

Error: declaration is incompatible with `sf::RenderWindow *Window::GetRenderWindow()`

In my Window class:

```
class Window{

public:
    ...
    sf::RenderWindow* GetRenderWindow();
    ...
private:
    ...
    sf::RenderWindow m_window;
    ...
}

```

I think it is probably because of the function declaration.

# Answer
sorry for the silly question. It is time to sleep I guess. Here is the corrected version:

```
sf::RenderWindow* Window::GetRenderWindow() {
    return &m_window;
}

```
> 0 votes

---
Tags: c++, sfml
---


# Question
Title: Simulating and predicting Box2D trajectories orbiting a planet
Okay, I have the following situation:

I want to launch a GameObject into orbit of a planet and using the dynamic rigidbody everything is working as I want. I simulate gravity and as it hits the surface again it bounces around nicely using the Box2D system.

However, I want to calculate the trajectory and visualise it on screen. I thought about it and came up with two solutions, but I run into some problems:

**1 Simplectic integration for the trajectory**

I simulate the trajectory using simplectic integration. However, as can be expected, the results are different for the dynamic rigidbody movement and the simplectic integration. This became very obvious when I launched two identical objects and simulated one dynamically and the other one simplectic. The code is as follows (all in `FixedUpdate`):

```
if (rb.isKinematic)
{
    velocity += forces / mass * Time.fixedDeltaTime;
    Vector2 newPosition = (Vector2)transform.position + velocity * Time.fixedDeltaTime;
    rb.MovePosition(newPosition);
}
else
{
    rb.AddForce(forces);
}

```

The simplectic / kinematic one is slower than the dynamic one. Weird.

**2 Use Physics2D.simulate**

According to https://docs.unity3d.com/ScriptReference/Physics2D.Simulate.html I can simulate it via code. However, this means that I have to set everything that is *not* to be simulated as disabled and simulate it for a given amount of time to calculate the trajectory. Not really what I was looking for, because I want to have a live trajectory update

**3 Full simplectic** That seems to be easy, but I want to have realistic collisions and bounces. Don't want to reinvent the wheel when Box2D should be sufficient.

**4 Simplectic for simple movement, dynamic at collision** This seems to be the logical candidate, but don't know if it is clever. Had no time to implement this yet, but should not be that difficult. Feels a bit icky...

**So, question?**

My questions are:

* Can I reduce or eliminate the offset from solution 1?
* If not, what whould be the most logical solution and / or am I missing one?

**EDIT** It was asked how I calculate the forces. This is simply Newton's law with squared distance:

```
public Vector2 CalculateForce(GameObject a, GameObject b) {
    // AUComponent is an interface type I have... not very special in itself.
    float mA = a.GetComponent<AUComponent>().Mass;
    float mB = b.GetComponent<AUComponent>().Mass;

    Vector2 r = b.transform.position - a.transform.position;
    return gravityConstant * mA * mB / r.sqrMagnitude * r.normalized;
}

```

However, the ever increasing offset is also happening with a constant force applied in a direction.

The masses of the AUComponent are equal to those of the RigidBody.

# Answer
If you are dealing with a shorter period of time (even uo to 30 seconds, but sometimes even more), then you can simply use the Euler method. You just take the object, save it's position and start simulating it's behaviour by stepping through the desired time period in smaller steps.

Thisbis actually something like what unity's simulate does, but you don't have to disable anything.
> 0 votes

---
Tags: unity, 2d, projectile-physics, planet, integration
---


title: Different z index within the same tile

text:
# Question
Title: Different z index within the same tile
When you are looking at this image:

the player is standing behind the tree. I know that can be accomplished by drawing the background first the player second and the upper tree part after that.

The thing is in the actual tileset there is only one tile that combines the background and the upper tree part:

So how is it possible that there are multiple z-indices within one tile. Or is the game somehow extracting the upper tree part from the base grass texture and draw them like described earlier?

# Answer
> 2 votes
As stated in the comments, that texture has a transparent background in the original game. That way they can just draw the base grass, then the player, then the tree.

---
Tags: rendering, tiles, draw-order
---


# Question
Title: What's the easiest way to get a JavaScript game to save?
I'm doing a re-skin of and old open source web game, the current game is in HTML, CSS and JavaScript.

I'm trying to redo the save game bit as I can't make sense of it and want something I can understand. I think it's relying on a database or Dropbox? Though I've tried removing the Dropbox links it still seems to work perfectly?

So it works but I don't understand what it's doing and I'd rather want something where I can see how its done, saving the state ie variable values and open panels etc.

# Answer
If you don't want the savegames to be actual files, then the easiest method would be to use localstorage. It allows your website to save several MB of key-value pairs in the user's web browser. The main advantages are that this is completely invisible to the user and does not require a server. The main problem with this is that savegame data is bound to the web browser. When the user wants to play on multiple devices, they can not easily transfer savegames.

Another option is to set up a server with a web API which stores the game states in a database. This will also require a user account system. The game you used as a template seems to use the Dropbox API for this.

You could also use the Javascript File API. This looks to the user as if they were uploading and downloading files on your website, even though they are only communicating with a local Javascript application. The user would then need to keep their savegames as a file on their device. This is less convenient for the user, but allows them to transfer savegames between devices.
> 2 votes

---
Tags: savegame
---


title: How can I generate a random 2D surface

text:
# Question
Title: How can I generate a random 2D surface
I'm trying to build an old game (Lander) where you try to land a spaceship on a flat platform.

But I have no idea how to generate a random surface. Something like in the picture would be nice.

Edit: I don't need a map generation like in Civilisation. I need a surface like hills and valleys.

I'm using QT but I think it's more a meta question than a framework question. Thanks!

# Answer
Unity code, but even so...

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

public class Terrain : MonoBehaviour
{
    //static members
    public const int HEIGHT_MAX = 10;
    public const int LENGTH = 30;

    //instance members
    int[] terrainPoints = new int[Terrain.LENGTH];
    GameObject[] terrainGOs = new GameObject[Terrain.LENGTH];
    public int scanRadius = 1;

    void Start ()
    {
        Camera.main.transform.position = new Vector3(0,0,-50); //zoom out a bit

        for (int i = 0; i < terrainPoints.Length; i++)
        {
            terrainPoints[i] = Random.Range(0, Terrain.HEIGHT_MAX);
            terrainGOs[i] = GameObject.CreatePrimitive(PrimitiveType.Cube);
            terrainGOs[i].transform.position = new Vector3(i, terrainPoints[i], 0);
        }
    }

    void Update ()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            Smoothe();
    }

    void Smoothe()
    {
        for (int selfIndex = scanRadius; selfIndex < terrainPoints.Length - scanRadius; selfIndex++)
        {
            int self = terrainPoints[selfIndex];

            //scan a local subset *including* self
            int sum = 0;
            int count = 0;
            for (int neighbourIndex = selfIndex - scanRadius;
                     neighbourIndex < selfIndex + scanRadius + 1;
                     neighbourIndex++)
            {
                int neighbour = terrainPoints[neighbourIndex];

                sum += neighbour;
                count++;
            }

            self = sum / count; //get the average over the sample diameter.
            terrainPoints[selfIndex] = self;
            terrainGOs[selfIndex].transform.position = new Vector3(selfIndex, self, 0);
        }

    }
}

```

Save as `Terrain.cs`, drop on any GameObject in the scene. Spacebar `Smoothe()`s the noise generated in `Start()`, you can do this repeatedly. You can use `scanRadius=1`, but the larger you make it via the inspector (e.g. 2, 3 and upwards) the more rapidly it will smoothe.
> 2 votes

# Answer
Well, I’d say that a simple noise function on the height of land on a certain point should be sufficient.
> 2 votes

---
Tags: 2d, procedural-generation, terrain, random, qt
---


# Question
Title: High-level advice on procedural river (Unity3D)
I'm working on some procedural content for Unity3D - in C#

My main aim is to build a flat plane (or maybe later a terrain / mesh), with a single river running through it, based on a seed value.

I will keep the river throughout, but I will have 2 versions of a settlement, one medieval, later one urban city-like.

The over-arching function is basically:

* Input an integer X (scale of settlement) and a seed integer Y
* build a river, maybe roads next if I get the time
* drop x buildings onto the map in a reasonable layout
* once x reaches a pre-defined limit, switch to urban generation

I will probably populate both with generic assets from the asset store or similar, and hopefully will layout the buildings with a decent algorithm.

I've so far been able to generate a reasonably nice Voronoi Diagram using CSDelaunay by PouletFrit

The plan is to maybe treat Voronoi cells as farms for the Medieval time, and then switch form Euclidean Distance formula to Manhattan Distance Formula later for city road generation (but always keeping the same river)

I've converted the 2D code to generate a visual 3D Voronoi Diagram to help me learn the process and how the classes all work.

## Examples

**2D Voronoi, applied to a Texture2D, dots are 'sites'**

**3D with graph edge midpoints**

I'm struggling with my next step from a planning point of view. In order to build a river through the diagram that looks reasonably well, I might use the method explained in Amit Patel's great procedural tutorial whereby splines are used, from edge midpoint to midpoint. and pick one arbitrary vertex on the north side, one on the south, and perform Dijkstra's algorithm to find the "best" (shortest) path for the river.

I have found a couple of very good spline tutorials such as the one from CatLikeCoding's AMAZING Curves and Splines tut.

but while writing this question I realised I have another option, I can just trace the edge midpoints and the cell 'sites' as in the image below, and increase the polygon (voronoi cell) count to make the river lines seem less angular. it's basic, but should work.

So my main problem now is analysing what to do next.

In theory I could stay working in 2D, build a texture that has rivers and maybe roads, maybe pick more pixel colours for trees, rocks etc, and then instantiate the necessaries into the 3D world. But I'm not sure this is the best approach.

I could instead generate a 3D river using some of the great code explained in "Unite 2015 - A coder's guide to spline-based procedural geometry" and embed it onto a plane or similar, but it's at this point I am getting stuck in analysis paralysis. I can't really decide/determine at a high-level the best way to move forward.

The main questions I am struggling with:

1. Should I generate a map of some sort in 2D and "extrude" details, or work in 3D from day one ? (main issue here is once I have a list of Vector3 for a river, how do I "apply" it to a plane or terrain ?
2. Should I use a "shortest path" algorithm for the river (traverse the graph in some way), or generate an independent sine wave with nice looking meanders based on sinuosity as per "Pi me a river"
3. Should I figure out a way to turn each Voronoi cell into a mesh and/or class so I can explore the relationships between two cells, or is it enough to finally figure out out how the graph data structure is working, and move from there.
4. I'm not sure how to layout the buildings later.

**Why a flat terrain ?**

I suppose it might be easier to maintain across the medieval and urban landscapes.

A nice-to-have would be some perlin-noise based terrain, which seems reasonably easy to generate a heightmap and build a terrain from there, but I'm pretty sure I will struggle to get any river algorithm I create to conform to the terrain properly, so I might stick to 2D for the moment.

I need to do this as much in code as possible, and hopefully I can write much of my own code rather than relying on libraries. However I'm not asking for any code help, just some advice to get me out of a rut, if anybody can help I would really appreciate it!

I realise that this sort of question may not be fitting the correct pattern for questions on the site, in which case I apologise, and you can close it off early.

Many thanks in advance.

# Answer
Why don't you just use the existing straightedges between each unique pair of voronoi cells - which are already natural boundaries - as river cells? You can just expand them widthwise, twist / splinify them and... voilà? You now have natural boundaries without having to split cells?

If you're ultimately going to be working in a 3D environment, then work in 3D from day 1. Unity and other 3D engines have 2D vectors supported in a 3D environment if you prefer to use those.

Your third question about meshes consists entirely in how you are going to use them. For now I would keep a separate mesh, but have superstructures that point the the start and end vertices of each island - we call these *submeshes* \- within that greater mesh.

As for your third question, neither are we. How can we be, when we have no idea what you'll be doing with them? These are the kinds of things you have to make your own road with - we all do. What I can say is you would probably be better off laying out buildings in a separate mesh so you can turn that view on and off while rendering, allowing you to see terrain more clearly.

Lastly, why flat terrain? Because it is always wiser to start with planar - which is computationally efficient and easier to reason about - and go to varying heights later, as in a heightmap. The one exception can be where you wish ultimately to have overhangs in terrain, e.g. in MineCraft - but even there, heightmaps are used as an intermediate structure e.g. in LoD and lighting.

**Conclusion** With this many ifs and maybes in your question, there is no way to do much better answers than that given here.
> 1 votes

---
Tags: unity, procedural-generation, splines, dynamic-mesh, delaunay-triangulation
---


# Question
Title: Latency issue on multiplayer game networking
I am currently writing a 2D top-down shooting multiplayer game using Java. I have a game loop at the client-side that does the following in order in each game tick (The client is running in a tick rate of 60 t/s):

```
client_gameloop{
    1. Send an input sample (an object storing info about what keys are pressed)
       to the server through a DatagramSocket
    2. Receive info on change in game state from the server
    3. Update the client-side game state through the received info
}

```

For the server-side, I have a game loop that does the following in order in each game tick (The server is running in a tick rate of 60 t/s):

```
server_gameloop {
    1. Read an input sample through a single DatagramSocket
    2. Using the input sample to apply physics to the game world and update the game state
}

```

When I try to connect the first client to the server, the game flows fluently with unnoticeable delay. However, when I try to connect the second client, both first and second client start to lag behind the server greatly (delay ranges from 5s to 10s). I am currently stuck on what causes the delay. Am I handling the sending and receiving of info between client and server in a wrong way that causes game state in the server-side not being able to synchronize with those of clients'?

# Answer
That is really big difference between one and two clients. The description of the server loop seem like you receive exactly one message each tick (at 60Hz). So when there are two clients sending messages, you would receive only from one client and then from the other client next tick, then from first one again, etc. So the queue of waiting messages would grow and the system would eventually start dropping messages when the receive queue is too long. That length could correspond to the 5-10s lag.

Make sure you receive all pending messages before going to wait for next week tick.
> 0 votes

# Answer
I'm by no means a networking or Java expert but I'll give it a shot.

Does the issue get worse the more clients you add? If so, I ran into a similar issue using node and websockets (I don't have any java experience).

For me, the problem was that I was simply sending too many packets to the server. On localhost it would work fine for up to two clients, but more, or a remote server, made everything very laggy.

I fixed my issue by only sending a client's input state to the server if the input actually changed. The server can just assume a client is still doing the same if it was not notified of any changes.

Server-Side it was also key to notify the clients only of the info they absolutely needed to reconstruct any changes that happened. Using interpolation for the other players was also a must (as 60t/s was neither feasible nor required for my scenario), introducing a frame or two of delay, but greatly reducing server-load.

So, to summarize:

* Try to only send updates to the server on input changes
* If required, try lowering the rate at which you update clients about other clients, but keep reading a client's input changes at 60t/s.
* Use inter/extrapolation to try and cover up the "holes" of data about the other players.
> 0 votes

---
Tags: networking, multiplayer, game-loop, client-server, udp
---


title: Implementing a UI in an android game

text:
# Question
Title: Implementing a UI in an android game
I have created a basic game that runs in a view. It consists of a thread which repeatedly calls the `update()` and `draw(Canvas canvas)` method. Everything works fine so far.

Next, I want to implement a UI that consists of a textView showing the score, and other stats of the game. This is put above the view of the main game. Should this UI have its own thread that repeatedly checks to see if the score has changed, and then update that change in the UI? At first I just made a class that allows the main game thread to update elements in the UI via something like `scoreView.setText(currentScore)`. But this leads to some instability, and that object to talk to the UI has to be passed throughout the methods in the main game UI which isn't the cleanest approach.

What is the standard approach for implementing the UI in a clean way which is easy to maintain.

visual guide: (the line indicates that the two communicate with another)

# Answer
```
using UnityEngine;

using UnityEngine.UI;

public class HitPoints : MonoBehaviour {

public Text HitPointsText;

    float hitPointsProp;
    public float HitPointsProp {
        get {
            return hitPointsProp;
        }
        set {
            hitPointsProp = value;
            HitPointsText.text = hitPointsProp.ToString();
        }
    }
}

```

Drag your Text game object to public field; When you will use HitPoints=10; the text will be automatically updated to 10.
> 1 votes

# Answer
I would suggest that you make use of DrawText. You can draw this using the existing thread that is drawing your current interface. You can change your variables anywhere in the code based on different conditions and you will know that what is being displayed is an up-to-date value as the thread will be checking/ drawing it so frequently.
> 0 votes

---
Tags: android, gui
---


title: Unity Player Movement Problem

text:
# Question
Title: Unity Player Movement Problem
I want to make a little game in Unity, where the player (a ball) jumps up and down and you have to maneuver it through (flappy bird like) obstacles.

My problem is, after I added a simple movement script:

```
float speed 10f;
Vector3 move = new Vector3(Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"), 0);
transform.position = move * speed * time.deltatime;

```

The ball is stuck and can only be moved a little,before returning to its start position.

My question is how i can fix that? I didnt find any solution

# Answer
The problem is in this line:

```
transform.position = move * speed * time.deltatime;

```

If the value of `move*speed*Time.DeltaTime` is lets say, (0,3), in that line of code you are not telling your transform to move (0,3) distance, but to set its absolute position to (0,3)

You should be updating the position of the player relative to it's current position:

```
transform.position = transform.position + move*speed*Time.DeltaTime

```

Or if you prefer a more compact line of code:

```
transform.position += move*speed*Time.DeltaTime

```
> 2 votes

---
Tags: unity, unityscript
---


# Question
Title: Vertices displaced when smoothing in Maya
The issue below appears when smoothing in maya. I would prefer to solve the problem normally as opposed to import/export obj.

Below the image is a .ma file you can download yourself.

File: https://www.dropbox.com/s/nhtc1uj2lvakjwf/reload.ma?dl=0

**Steps Taken To Isolate Problem**

-Issue does not occur when doing a smooth mesh preview with the EXCEPTION of 1 face

-Deleted face. Error moves up another face.

-Continued to delete the face ring one face at a time and noticed the error moves up.

-Selected face ring, delete and rebridged. Fixed.

-Infered that the root cause of the problem has something to do with the way I created face ring or edge ring.

-The issue only occurs in this one mesh object.

-Deleted all items in the scene except the problem mesh and saved an isolated file.

-Deleted UVs.

-Deleted history.

-Optimized scene.

-Cleaned mesh with the following settings.

-Select matching polygons.

-Apply to selected objects, Keep Construction History.

-Lamina faces.

-Nonmanifold geometry, Normal and geometry.

-Merged all vertices with a tolerance of 0.01.

-Unlocked normals.

-Ensured normal directions were correct.

-Ensured there were no faces inside of edges.

-Issue ONLY occurs with 1 subdivision.

-Hardened all the edges.

-Exported and reimported OBJ. Again, I do not want the lazy solution, I want the correct one. I did this so I can infer that the root cause is not mesh-related.

-Combined with cube

-Deleted history (again)

-Optimized scene (again)

-Cleaned mesh (again)

**Specs**

Maya Version: Maya 2016.5 Ext 2 (64bit)

OS: Windows 10 Pro (Build: Latest)

Video Card: Nvidia GeForce 980 X (Driver: Latest)

CPU: Intel Core i7 3930K

**Mirror Threads**

http://polycount.com/discussion/198641/maya-2-vertices-displaced-when-smoothing/p1?new=1

# Answer
> 1 votes
**Root Cause**

-The theory is that the issue is caused by merging vertices on an enclosed border. Half the time it works as expected, the other half it will bug out. (thanks to polycount user throttlekitty and poopie)

**Resolution**

-Combining 2 objects by merging vertices is bad practice. In order to avoid this bug, do the following

-Select edge

-Shift + Right Click, and choose to merge border edges

-Alternatively, you can bridge the edges.

-Thanks to Polycount user throttlekitty and poopie

---
Tags: rendering, 3d-meshes, maya
---


# Question
Title: Libgdx Scene2D second screen animating and accept input while still loading
I'm currently developing an app Scene2D that involves a small number of screen switches. I am having a problem that after calling set screen there appears to be a pause of a second or two (I think it's the non UI logic is being performed in the new screen constructor to aid setting up UI actors), which is fine. But during that second pause. It appears my second screen is already running in the background but not being rendered. I think this is happening because of two problems:

* Animations and Actions that are supposed to begin when the second screen loads are already one or two seconds in progress by the time the second screen loads.
* During the pause before the second screen loads, the first screen is still rendered in freeze frame, but any user input is queued and processed in the second screen after it renders! Meaning that the user is effectively clicking on things that are not yet rendered which can cause some problems for their experience.

I already am setting the input processor in the show method but it show appears to be called before the screen is actually visible and rendering frames.

Is there something I have misunderstood about the life cycle? Or common pitfalls I may have fallen into? Only a problem on Android, Desktop is fine but possibly only because the loading times are too fast to notice either problem.

# Answer
> 0 votes
Your suggestions are right.

You should try something like this :

```
// In init
boolean rendering = false;

```

And in your render method

```
// In render loop
if (!rendering)
{
    rendering = true;
    /* Do your stuff that should be on done on first rendering,
    like setInputProcessor, add animations etc /*
}

```

The flag is just to do everything once. I think this might work, give it a try

# Answer
> 0 votes
Can you tell which screen should be drawn next? If you want to draw a pause menu, you should load it at the creation of you game screen as the pause menu could be pressed often and you dont want to load 1/2 seconds each time.

I think a better option than the mentioned above looks like this: You do create everything in the cunstructor and on the very end you add the logic than should only happen if you can actually see it (the 1/2 seconds after the start of the new screen)

This avoids checking a boolean each frame.

---
Tags: android, libgdx, scene2d
---


# Question
Title: Flipping a 3D text around its Y axis SharpGL
```
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private readonly MainViewModel _mainViewModel;
    private float _rotation;
    public MainWindow()
    {
        InitializeComponent();
        _mainViewModel = new MainViewModel();
        DataContext = _mainViewModel;
    }
    private void OpenGLControl_OpenGLInitialized(object sender, OpenGLEventArgs args)
    {
        OpenGL gl = args.OpenGL;
        gl.Enable(OpenGL.GL_DEPTH_TEST);
        gl.ShadeModel(OpenGL.GL_SMOOTH);
    }

    private void OpenGLControl_OpenGLDraw(object sender, OpenGLEventArgs args)
    {
        OpenGL gl = args.OpenGL;

        // Clear The Screen And The Depth Buffer
        gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);

        // Move Left And Into The Screen
        gl.LoadIdentity();
        gl.Translate(0.0f, 0.0f, _mainViewModel.Zoom);

        if (_mainViewModel.Rotate)
        {
            gl.Rotate(_rotation, 0.0f, -1.0f, 0.0f);
        }

        gl.Color(_mainViewModel.RgbColors[0], _mainViewModel.RgbColors[1], _mainViewModel.RgbColors[2]);

        gl.DrawText3D("Mazor", (float) 30.0, (float) 1.0, (float) 0.5, "Mazor");

        _rotation += 3.0f;
        gl.Flush();
    }
}

```

I would like to flip the 3D text I have around y axis, I am able to do so, However I want the word "Mazor" to flip around the middle of the word, and not around the left side of the word.

if you run the code you can see the rotation occurs around the M letter, where as I would like to change the y axis to be where the Z letter is. Can you please help ? Thanks

# Answer
> 1 votes
You'll need to first translate the modelview matrix so that the middle of the word is at the origin, do your rotation, and then translate it back to its previous position. So something like this:

```
    if (_mainViewModel.Rotate)
    {
        gl.Translate(0.0, 0.0, -(_mainViewModel.zoom + textWidth / 2.0));
        gl.Rotate(_rotation, 0.0f, -1.0f, 0.0f);
        gl.Translate(0.0, 0.0, _mainViewModel.zoom + textWidth / 2.0);
    }

```

This assumes that the width of the text is stored in a variable named `textWidth`.

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


# Question
Title: How do I know my VRAM upload is ready to be used?
Previosuly in Direct3D 9 and 11, if I wanted to update a resource in a Default heap, for example, a Vertex Buffer, I would lock the memory of the buffer, copy the data to the returned pointer, and then unlock the buffer. It is my understanding that unlocking the buffer committed the data to VRAM, and I could be certain that the buffer would be ready to be used by any draw commands.

With Direct3D 12, we now have the concept of upload heaps, and instead of locking the buffer each time I want to modify it, I can just get a mapped pointer to the VRAM area with `ID3DResource::Map()`. This is pretty cool, because I understand that in most cases, the write is performed with write combining, so I don't have to wait until the entire data is committed to VRAM to keep on doing work on the CPU.

Now the question is, how can I ensure that when I execute a GPU command that references that memory, the memory is already committed, and the GPU can safely read it?

# Answer
> 1 votes
You can't render using the part of a resource with uncommitted memory. You create the GPU VRAM resource using `CreateCommittedResource`.

You should think of a `D3D12_HEAP_TYPE_UPLOAD` like the DirectX 11 `STAGING` resource. You can lock it because it's CPU accessible, and then use the GPU to copy data from the upload heap to your commited resource in the `DEFAULT` heap which may or may not be CPU accessible. You have to use a fence to make sure the GPU copy is complete before you can render with it, otherwise you risk changing the data while rendering it.

> See DirectX Tool Kit for DX 12 and in particular the `ResourceUploadBatch` helper class.

---
Tags: directx12
---


title: Double Click Unity

text:
# Question
Title: Double Click Unity
Have a class, which I am calling from PointerClick(in EventTrigger).
Need to recall PointerClick after the first PointerClick((0.2f) seconds later).

# Answer
1. Make sure you have a PhysicsRaycaster or Phyics2DRaycaster on your camera if the object holding this script is a 3D / 2D object. If it's a UI object, you have to put a GraphicRaycaster
2. Make sure the object holding this script has a Collider or Collider2D or an Image/RawImage component with `RaycastTarget` checked
3. Make sure you have an EventSystem in your scene

---

```
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class ClassName: MonoBehaviour, IPointerClickHandler
{
    public float doubleClickThreshold = 0.2f ;
    public UnityEvent OnDoubleClickDetected;
    private float lastClickTime = -1 ;

    public void OnPointerClick(PointerEventData ped)
    {
         if( Time.time - lastClickTime < doubleClickThreshold )
         {
             if( OnDoubleClickDetected != null )
                 OnDoubleClickDetected.Invoke() ;
         }
         lastClickTime = Time.time ;
    }
}

```
> 0 votes

# Answer
Not sure if I understood but you can try: Invoke( method(), time ); to call some method after certain time

documentation: https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
> 0 votes

---
Tags: unity, events, clicker
---


# Question
Title: How to reduce the time taken to path-find to an unreachable location?
I have a 2048x2048 map and if I *path-find* to an unreachable location, it makes the pathfinder go through every node on the map which freezes the thread for 4 seconds.

How can I reduce that time?

* I'm using JPS
* It's a dynamic map (it changes at runtime)

# Answer
> 18 votes
Using a bidirectional path finder usually solves this issue if the area the player is stuck in is small. They basically advance from the player's position and the destination at the same time and when they meet, the algorithm ends. If one of them gets stuck, then you can stop both.

# Answer
> 13 votes
You should make a sort of connectivity map - by flood-filling all unconnected walkable areas and marking each one with a different tag, once at game start (and every time when terrain changes). Then, before even trying to make a path, check if source and destination locations belong to areas with the same tag, if not - path obviously can not be made.

Additionally, you could discard all isolated unreachable areas from pathfinding at all.

# Answer
> 3 votes
Add a "maximum number of iterated nodes" parameter to your pathfinding algorithm. When the limit is reached, simply give up and claim that there is no path.

---
Tags: path-finding, optimization
---


title: Unity - Fading mesh particles

text:
# Question
Title: Unity - Fading mesh particles
Is there any ways to fade mesh particles like color over lifetime method with addictive shader. I have little to no understandings of shader coding, and fade rendering issue kicks in even with vertex color shader. Any idea guys?

# Answer
In a very general way of an answer, fading particles is done by reducing the colour or, more commonly, the alpha value (opacity) of the particle, as a function of time. The colour values of a particle are usually (R,G,B,A).

We can say that at the beginning of a particles lifetime, it's opacity should be 1.0, and when it's lifetime reaches zero, it's opacity should also be zero.

So let's say that the particles lifetime is 5 seconds, and that an average update is 16 milliseconds, or 0.016 seconds.

From this, we know that the rate of change in opacity will be -0.2 opacity per second (-1.0/5.0).

Now that we know how fast to reduce the particles opacity per second, we can interpolate per update:

```
Op + dOp * dT = Op'

```

first step follows:

```
1.0 + (-0.2 * 0.016) = Op'

= 1.0 + (-0.032) = 0.9968

```

If the particle effect is continuous, then when lifetime reaches 0, you can reset it's position to the emitter and set it's opacity back to 1.0.

Alternatively:

```
Op = current lifetime/max lifetime

```

This is simpler percentage based computation of opacity.

How you actually update the current values is more implementation specific, so I suggest you do some reading into Unity shader coding, to get comfortable with the basics, then experiment with the above information.
> 1 votes

---
Tags: unity, shaders, particles
---


# Question
Title: Mouse position not updating while mouse buttons are pressed
I have a simple mouse manager class: https://i.stack.imgur.com/EIcEt.jpg

Whenever any of the mouse buttons are pressed the mouse position does not update when calling `getMouseX()` or `getMouseY()` on the mouse manager object via a basic handler that gets passed everywhere.

Is the problem in my implementation or is it a bug in general?

# Answer
The problem is with your implementation.

Change your button handling code to something like :

```
if (e.getButton() == MouseEvent.Button1) {
    leftpressed = true;
    mouseX = e.getX();
    mouseY = e.getY();
}

```

Basically you want to update the stored mouse position on all mouse events.
> 2 votes

---
Tags: java, mouse
---


# Question
Title: Why does this floor() call appear to have no effect?
I'm trying to get an effect where my material forms a mosaic which is aligned to the material. So I slapped a simple quad in the scene with a new material on it and set a new shader to that material.

My inputs (at least one thing in here will be removed later since it turns out I'm not using it):

```
        struct Inputs
        {
            float4 vertex : POSITION;
            float2 uv_panel : TEXCOORD0;
        };
        struct FragmentData
        {
            float4 vertex : POSITION;
            float4 uv_grab : TEXCOORD1;
        };

```

Vertex function:

```
        FragmentData Vertex(Inputs i)
        {
            FragmentData o;

            o.vertex = UnityObjectToClipPos(i.vertex);

            // what I actually want to do (the exact maths might be
            //   wrong still):
            float2 uv_panel = floor(i.uv_panel * _Pixels) / _Pixels;

            // Convert that UV value for inside the panel
            // to a UV value for the grab texture
            float4 object_coords = float4(0, 0, 0, 1);
            object_coords.xy = uv_panel - 0.5;
            float4 clip_coords = UnityObjectToClipPos(object_coords);
            o.uv_grab = ComputeGrabScreenPos(clip_coords);

            return o;
        }

```

And then the fragment function is pretty trivial:

```
        half4 Fragment(FragmentData i) : COLOR
        {
            return tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(i.uv_grab));
        }

```

The end result is basically equivalent to doing nothing at all. I can see the objects behind the quad as if it weren't there. Upside is that it means my transformations are correct. Downside is that it means the mosaic effect somehow isn't being applied.

To check whether the floor call was working (and because I currently know no better way to debug this crap) I tried applying it like so:

```
            float2 uv_panel = floor(i.uv_panel);

```

This has no effect either.

This seems odd to me, because I thought uv\_panel values in x and y would range from 0.0 to 1.0, so almost all values should floor to 0.0.

When I do this:

```
            float2 uv_panel = float2(0, 0);

```

It acts like I expected, with the bottom of the grab texture being smeared up the panel with the panel's alignment. So it's definitely using whatever value I put in here.

At this point I have no idea how to proceed because it's like my assumptions about the values in a `float2:TEXCOORD0` are completely incorrect, or the `floor()` function does something completely different to what I expected.

What am I doing wrong here?

# Answer
> 2 votes
You're using floor in your vertex shader, which runs only once for each vertex.

So if you're rendering a standard quad or a blit pass, it only sees 4 UV values: `(0, 0)`, `(0, 1)`, `(1, 0)`, `(1, 1)`. And for numbers like these (if `_Pixels` is an integer), your formula is a no-op:

```
   floor( (0, 1) * _Pixels ) / _Pixels
   = floor( (0, _Pixels) ) / _Pixels
   = (0, _Pixels) / _Pixels
   = (0, 1)

```

For each fragment rasterized to the screen, these UV values output by the vertex shader are interpolated. The interpolation unit has no knowledge of how those numbers were calculated, so it doesn't know to perform a floor evaluation in between.

Instead, if you want to get a flooring or any other effect that varies pixel-by-pixel across a triangle, rather than only vertex-by-vertex, you'll want to put it into the fragment shader, which runs for every rasterized fragment individually.

---
Tags: unity, shaders, vertex-shader
---


# Question
Title: Why is the position of this image changing?
I have a python script to simulate a wrench moving, I have calculated it's origins position in x and y as a function of time, the problem is when I try to rotate the image, my code moves the image out of frame.

```
import pygame, sys
import math

screen = pygame.display.set_mode((700, 400))
wrench = pygame.image.load('prueba.bmp')
white = (255,255,255)

ox = 20
oy = 32
running = True
posX = 100 - ox
posY = 100 - oy

pygame.init()
while running:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running=0
        screen.blit(wrench, (posX, posY))
    if(pygame.time.get_ticks() <= 20000):
            screen.fill(white)
            t = pygame.time.get_ticks() / 1000
            print(t)
            ang = math.degrees((math.pi / 2 * math.cos(math.pi * t)))
            posX = 100 + (50 * math.cos(math.pi * t)) - ox
            posY = 100 + (20 * math.sin(math.pi * t)) - oy
            wrench = pygame.transform.rotate(wrench, ang)
            screen.blit(wrench, (posX, posY))
    pygame.display.flip()

```

Does anybody knows why this is happening?

# Answer
I'm not very familiar with Python, but I believe it's because of this line:

```
wrench = pygame.transform.rotate(wrench, ang);

```

wrench is updating itself, and the origin of rotation \<0,0\> will be in a different place with respect to the image each time. This is because the wrench's bounding rectangle is being updated as it turns.

To fix the problem, keep track of the rotation angle, and rotate the raw image only.

```
rotated_wrench = pygame.transform.rotate(wrench, ang);

```
> 1 votes

---
Tags: python, pygame
---


# Question
Title: OpenGL calculate circle rotation around a given point
I'm trying to rotate an object around a certain point. If this point is the center of my world space I use the following algorithm:

`glm::vec3 center` is the center of the current object. Each frame it will get updated.

`glm::mat4 transformationMatrix` is the 4x4 matrix I am "uploading" to my shader later on. It will get multiplied by the vertex position.

`t_point` is the point I'd like to rotate around

`t_deflection` is the impact for each axis (in order to draw ellipses instead of circles)

`t_speed` is in my case the current time since the game started (e.g. `glfwGetTime()`)

```
void rotateByPointY( const glm::vec3& t_point, const glm::vec3& t_deflection, const float& t_speed )
{
    float radius = glm::length( t_point - center );

    glm::vec3 newPosition( glm::sin( t_speed ) * radius * t_deflection.x, center.y, glm::cos( t_speed ) * radius * t_deflection.z );

    translationMatrix = glm::translate( glm::mat4( 1.0f ), newPosition );
    center = newPosition;
}

```

**How can I take into account a point other than the center of my world in the calculation?**

EDIT:

So my `rotateByPointY` calculates the translation around the world center. Therefore I am adding the new center vector to my new position:

```
translationMatrix = glm::translate( glm::mat4( 1.0f ), newPosition + t_point );
center = newPosition + t_point;

```

That is working now!

# Answer
> 2 votes
You first need to translate the objects, so that the center point falls on (0,0,0), this basically make everything centered around that. Then you can just rotate the object and then translate everything back.

---
Tags: opengl, c++, linear-algebra, glm
---


# Question
Title: how to do client side prediction with server side collision detection?
I recently started working on my first multiplayer game and learning multiple game server mechanics. The game itself uses mouse movement.

For the first version I used a very simple approach, where the physics are run both on the client and the server side, and the client and the server both run at 60fps. The client only renders what it gets from the server and every collision/movement is processed server side.

Now every frame the client sends his mouse position to the server, where the players next position is processed and sent back to the player. This approach worked for some time, but at the time of writing the code, I didn't take the latency in account. For really good internet connections or locally for me, there isn't any issues, but for not so good internet connections there's lag obviosly.

So I started searching for a solution to my problem and I found this article - http://www.gabrielgambetta.com/client-side-prediction-server-reconciliation.html

I implemented the Client Side Prediction to my game with the Server reconciliation but now I noticed another problem. Because the collision detection happens server side, I can see that sometimes the collision happens much later than it should. Pretty obvious because the server is in the past.

So I was thinking, what would be the best solution to this problem? I could move the collision detection to the client side, but we all know, that the player can't be trusted, so I would need a way to verify this collision server side. And what if the player tampers with the code and disables collision detection (because some of these collisions are deadly), how could I known when the collision is happening?

Another issue I though of with the client side prediction, is if the player throws a grenade at some other player, but in reality the other player isn't at the specific position yet, because his position was also predicted. What would be the best way to handle this?

You can see my current approach here, which doesn't use the client side prediction at all

The client side of my game uses Phaser, but the server P2.js physics library.

This is how the movement happens without client side prediction

Client Side

```
let pointer = game.input.activePointer;

//Send a new position data to the server
socket.emit('move-pointer', {
    pointer_x: pointer.x,
    pointer_y: pointer.y,
    pointer_worldx: pointer.worldX,
    pointer_worldy: pointer.worldY,
});

```

Server Side

```
//Make a new pointer with the new inputs from the client.
        //contains player positions in server
        let serverPointer = {
            x: data.pointer_x,
            y: data.pointer_y,
            worldX: data.pointer_worldx,
            worldY: data.pointer_worldy
        };

        //moving the player to the new inputs from the player
        if (PositionService.distanceToPointer(movePlayer, serverPointer) <= 30) {
            movePlayer.body.angle = PositionService.moveToPointer(movePlayer, 0, serverPointer, 100);
        } else {
            movePlayer.body.angle = PositionService.moveToPointer(movePlayer, movePlayer.speed, serverPointer);
        }

        let x = movePlayer.body.position[0];
        let y = movePlayer.body.position[1];

        let radius = movePlayer.size + (movePlayer.shield / 2);

        if (x <= (1000 + radius)) {
            movePlayer.body.position[0] = 1000 + radius;
        }

        if (y <= (1000 + radius)) {
            movePlayer.body.position[1] = 1000 + radius;
        }

        if (x >= (game.properties.height - radius)) {
            movePlayer.body.position[0] = game.properties.height - radius;
        }

        if (y >= (game.properties.width - radius)) {
            movePlayer.body.position[1] = game.properties.width - radius;
        }

        movePlayer.x = movePlayer.body.position[0];
        movePlayer.y = movePlayer.body.position[1];

        //new player position to be sent back to client.
        let info = {
            x: movePlayer.body.position[0],
            y: movePlayer.body.position[1],
            angle: movePlayer.body.angle,
            speed: movePlayer.speed,
            ts: data.ts
        };

        //send to sender (not to every clients).
        this.emit('input-received', info);

```

Client Side, on input-received

```
        //we're forming a new pointer with the new position
    let newPointer = {
        x: data.x,
        y: data.y,
        worldX: data.x,
        worldY: data.y,
    };

    let distance = PositionService.distanceToPointer(player, newPointer);
    let speed = distance / 0.06;

    player.rotation = PositionService.moveToPointer(player, speed, newPointer);

    if (this.map_group) {
        player.map.x = (player.x / (this.properties.server_width / 220)) - 20;
        player.map.y = (player.y / (this.properties.server_height / 220)) - 20;
    }

```

PositionService class

```
class PositionService {

/**
 * @param displayObject
 * @param speed
 * @param pointer
 * @param maxTime
 * @param angle
 * @returns {number}
 */
static moveToPointer(displayObject, speed, pointer, maxTime, angle) {
    if (maxTime === undefined) { maxTime = 0; }

    if(typeof angle === 'undefined'){
        angle = PositionService.angleToPointer(displayObject, pointer);
    }

    if (maxTime > 0) {
        //  We know how many pixels we need to move, but how fast?
        speed = PositionService.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
    }

    displayObject.body.velocity[0] = Math.cos(angle) * speed;
    displayObject.body.velocity[1] = Math.sin(angle) * speed;

    return angle;
}

/**
 * @param displayObject
 * @param pointer
 * @param world
 * @returns {number}
 */
static distanceToPointer (displayObject, pointer, world) {

    if (world === undefined) { world = false; }

    let dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.body.position[0] - pointer.worldX;
    let dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.body.position[1] - pointer.worldY;

    return Math.sqrt(dx * dx + dy * dy);
}

/**
 * @param displayObject
 * @param pointer
 * @param world
 * @returns {number}
 */
static angleToPointer (displayObject, pointer, world) {

    if (world === undefined) { world = false; }

    if (world) {
        return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x);
    }
    return Math.atan2(pointer.worldY - displayObject.body.position[1], pointer.worldX - displayObject.body.position[0]);
}
}

```

# Answer
It is worth to mention what a client side prediction is. It is technique to perform a prediction of what an authoritative server will compute and respond with. Therefore this prediction should include, based on business or gameplay requirements, any logic that server performs but client wants to predict it to mimic no or low latency overhead. That is used to locally (client side) show more "present" state of the game - if prediction is correct enough, player will not even notice it while not feeling actual latency; if prediction is wrong (the higher lag, the higher chance of wrong prediction) then player will see these explicit snapping of position, etc.

In your case, exactly as DMGregory said in his comment, you should consider collision logic on the client side as well as it is your core gameplay mechanics that highly impacts the end user experience.

When it comes to your grenade example, it is very wise question and there is no "one size fits all" solution to this and different games implement it differently depending on high level aspects like genere or even low level aspects like what weapon player used in this case. Check out this guide which Valve provides for Source Engine. There is described server side lag compensation mechanism that is used to favor players and what they see in their client applications.

In the end, it is up to game developer to decide what is important to be included in client/server side lag compensation solutions and it often will be a trade-off of user experience and solution complexity.
> 0 votes

---
Tags: multiplayer, lag, movement-prediction
---