# Question
Title: Transforming world to canvas goes wrong when camera is moving
I am attempting to draw a box around a selected target in my space game. I had this working fine using normal techniques when my canvas was set to Screen Space - Overlay. However my setup is that ship models are fully present and physical and inside the cockpit of each one there is a "CameraRig" transform that by default the player camera attaches to unless they are free looking or moving around the ship.

With this setup the GUI would draw over the walls of the ship and it looked silly so I changed the canvas type to Screen Space - Camera and set a plane distance so that the gui was outside of the ship. I modified my box calculations to use RectTransformUtility to convert the existing screen position to canvas position.

This all works fine when the game is first ran and the ship is sat looking at a sun positioned at 0, 0, 0:  and it renders correctly if I free look the camera around. However the moment I set a new target and the ship starts rotating and moving towards it something goes wonky and target boxes appear in strange places, often directly to the side or above/below so i have to free look around to find them and often with wrong width/height. Here is an example where the planet im moving towards is centered but the target reticule is off to the side and will ultimately not be visible unless i hard look left:

If I then fly back to the sun often the shape of the box will be wrong and slightly maligned, so I feel like this is to do with the cameras position and rotation. But I cannot control it, its hard attached to the camera and controlled by unity and the unity methods I've used to calculate the position are supposed to account for camera position/rotation, right?

My code (edited to only show relevant):

```
var center = targetRenderer.bounds.center;
var extents = targetRenderer.bounds.extents;

var worldCorners = new[] {
    new Vector3( center.x + extents.x, center.y + extents.y, 0 ),
    new Vector3( center.x + extents.x, center.y + extents.y, 0 ),
    new Vector3( center.x + extents.x, center.y - extents.y, 0 ),
    new Vector3( center.x + extents.x, center.y - extents.y, 0 ),
    new Vector3( center.x - extents.x, center.y + extents.y, 0 ),
    new Vector3( center.x - extents.x, center.y + extents.y, 0 ),
    new Vector3( center.x - extents.x, center.y - extents.y, 0 ),
    new Vector3( center.x - extents.x, center.y - extents.y, 0 ),
};

var screenCorners = worldCorners.Select(corner => cam.WorldToScreenPoint(corner)).ToArray();

var canvasCorners = screenCorners.Select(c =>
    {
        c.z = 0;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, c, WorldCanvas.worldCamera, out var transformedPoint);
        return transformedPoint;
    }
).ToList();

var screenCorners = worldCorners.Select(corner => cam.WorldToScreenPoint(corner)).ToArray();

var canvasCorners = screenCorners.Select(c =>
    {
        c.z = 0;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, c, WorldCanvas.worldCamera, out var transformedPoint);
        return transformedPoint;
    }
).ToList();

maxX = canvasCorners.Max(corner => corner.x);
minX = canvasCorners.Min(corner => corner.x);
maxY = canvasCorners.Max(corner => corner.y);
minY = canvasCorners.Min(corner => corner.y);

var width = maxX - minX;
var height = maxY - minY;
var posX = minX;
var posY = minY;

GuiImage.anchoredPosition = new Vector2(posX, posY);

GuiImage.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
GuiImage.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, height);

```

if you would like to see full update method unedited then here is a paste: hastebin (scaleby is 0, usedeltas is false).

The camera the player is looking through and the camera used by the canvas are the same camera.

I am at a complete loss as to why it is behaving this way. Welcome all input!

# Answer
> 0 votes
I realised an old test blanked out the Z in the worldCorners to just 0 and was never reverted for future refactors - I later fixed my bug but this remaining meant the screen position step was never completely accurate - except for an object at 0, 0, 0 - the sun!

For anyone attempting this in the future the correct steps are:

* Calculate the corners of the object in world space using their center and extents in above code (add in Z)
* Convert them to Screen Space using the WorldToScreenPoint method in your camera
* use RectTransformUtility.ScreenPointToLocalPointInRectangle to convert to the canvas space by passing in your canvas RectTransform, the position and the camera used by your canvas.

You can now use these corners to calc the x/y and width/height. When using with a Image component you should set the anchoredPosition and set the width height using SetSizeWithCurrentAnchors.

Final caveat,this expects the image anchor (position and pivot) to be set to center else everything will appear misaligned. Hope this saves someone some time.

Edit: Extra thing I encountered after all this and how to fix it for future searchers: if as you move around you find your canvas elements shaking/vibrating lots you can mitigate it by selecting your camera and changing the Near Clipping Plane value to something higher than the default 0.3 - the higher it is the less shake so the highest that works for your game.

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


# Question
Title: Efficient way to detect when audio clip ends
In Unity, I want to trigger an event when an audio clip finishes playing. Would it be more CPU efficient to keep checking if the audio clip is playing with

```
WaitUntil(() => audioSource.isPlaying == false);

```

or would it be more efficient to use:
`WaitForSeconds(audioClip.length);`
to simply wait a certain amount of time?

How can I run a test in Unity to see which one is more CPU efficient?

# Answer
`isPlaying` will also return false if the song gets paused via. `Pause`.

Therefore I'd recommend waiting for the `clip.length` instead. Be aware tough this will only work in case your song plays with a `pitch` of 1.

Anything else will cause the `AudioSource` to play faster or backwards and therefore the `WaitForSeconds` call doesn't actually wait until the song ends.

---

Instead of thinking about which Wait call to use, it would probably make much more sense to ensure you cache the `WaitForSeconds` or `WaitUntil` call.

This is helpful because the new keyword heap allocates the given class meaning it has to be garbage collected once it is not used anymore. If you instead create it at the start of the coroutine and reuse it. You can save precious garbage allocations, which especially for low end devices (Phones etc.) can make a huge performance difference.

---

**Method to actually wait until the clip ends:**

There is still one drawback if you increase/decrease the `pitch` while the `Coroutine` has already started the `WaitForSeconds` call will still be off by the given pitch difference.

```
private IEnumerator ExampleCoroutine(AudioSource source) {
    // Cache the WaitForSeconds call, this is done because
    // like any other class WaitForSeconds causes garbage because it is heap allocated.
    // Therefore we cache it to simply reuse the same class instance.
    var waitForClipRemainingTime = new WaitForSeconds(source.GetClipRemainingTime());
    yield return waitForClipRemainingTime;
    // Trigger event here!
}

```

**Needed ExtensionHelpers:**

```
using UnityEngine;
using UnityEngine.Audio;

public static class AudioSourceExtension {
    public static bool IsReversePitch(this AudioSource source) {
        return source.pitch < 0f;
    }

    public static float GetClipRemainingTime(this AudioSource source) {
        // Calculate the remainingTime of the given AudioSource,
        // if we keep playing with the same pitch.
        float remainingTime = (source.clip.length - source.time) / source.pitch;
        return source.IsReversePitch() ?
            (source.clip.length + remainingTime) :
            remainingTime;
    }
}

```
> 3 votes

---
Tags: unity, events, audio, efficiency
---


# Question
Title: How to use Unity job system to do background work spanning multiple frames?
I have a slow level generation algorithm that freezes the main thread when it runs. I found this post which is exactly the same problem, but predates the Jobs system.

All the jobs examples I found are good for parallelizing a bunch of instances of some function but the `JobHandle.Complete()` still pauses the main loop until they are done. Is there a way to offload a function that will take several frames to complete with Jobs?

Or am I better off creating a thread manually as suggested in that other post?

Thanks

# Answer
> 1 votes
## EDIT

The Jobs based answer below can work.

But for anyone who has use case I had (one expensive level generator algorithm to run in background rather than many parallel ones), just using Async/Await Tasks requires much less refactoring. This video was helpful:

https://www.youtube.com/watch?v=oWFJl56IL4Y

---

## Original answer

This seems to work. I didn't realise that it will launch scheduled jobs even if you don't call `Complete();`.

In fact the job will execute even if you don't call `JobHandle.ScheduleBatchedJobs();`  but the docs seem to say you should call that, so I'm assuming in more complex code there can be a condition when the job won't pick up. Perhaps I'm wrong about this.

ScheduleBatchedJobs docs

```
public class JobTest : MonoBehaviour
{
    JobHandle myJob;
    bool started = false;
    bool done = false;
    void Update()
    {
        if (!started)
        {
            if (Time.realtimeSinceStartup > 5)
            {
                print("scheduling");
                myJob = scheduleLongJob();
                JobHandle.ScheduleBatchedJobs();
                started = true;
            }
        }

        if (myJob.IsCompleted && started)
        {
            myJob.Complete(); // do I need this? What does it do in this case?
            print("job completed");
            done = true;
        }
    }
    JobHandle scheduleLongJob()
    {
        LongJob myJob = new LongJob();
        return myJob.Schedule();
    }
}

public struct LongJob : IJob
{
    public void Execute()
    {
        float u = 0;
        for (int i = 0; i < 50000000; i++)
        {
            u += math.exp10(math.sqrt(10f));
        }
        Debug.Log(u);
    }
}

```

---
Tags: unity, multithreading, unity-job-system
---


# Question
Title: How to move an object when a specific event occurs?
```
public void LetsGO()
{
    elapsedTime += Time.deltaTime;
    float percentageComplete = elapsedTime / desiredTime;

    transform.position = Vector3.Lerp(startPos, MoveHere, Mathf.SmoothStep(0,1, percentageComplete));
}

```

This works when I put in Update. But the thing is, I want this object to move the moment a specific action has been triggered. But it literally moves only one frame each time a specific action has been initiated from TriggerEnter2D. Is there a way to make it perform the full movement after it's been triggered?

This is the action that's been called via Unity Event.

```
public void ChangeArena(int ChangedTime)
{
    DangerTouched += ChangedTime;
    if (DangerTouched > 3)
    {
        NewPlatform?.Invoke();
    }
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "First")
    {
        AddScore(1);
    }

    if (collision.gameObject.tag == "DangerFirst")
    {
        ChangeArena(1);
    }
}

```

# Answer
> 2 votes
I am not a fan of coroutines, because they make it hard to reason what actually goes on in the code. I prefer to use a pattern like this:

```
public class MoveOnTrigger : MonoBehaviour {

     private bool isGoing;
     private float elapsedTime;
     public float desiredTime;

     void Update() {
           if (isGoing) {
               elapsedTime += Time.deltaTime;
               float percentageComplete = elapsedTime / desiredTime;
               transform.position = Vector3.Lerp(startPos, MoveHere, Mathf.SmoothStep(0,1, percentageComplete));

               if (percentageComplete >= 1.0f) {
                   isGoing = false;
               }
           }

     }

     public void LetsGo() {
          elapsedTime = 0f;
          isGoing = true;
     }
}

```

The gist is that you do your movement in `Update`, but have a bool variable (`isGoing` in this case) which prevents that code from running. When the triggering event happens, you set that variable to true, and the movement begins.

Also note that this code allows you to repeat the action from the beginning by calling `LetsGo()` again. This is achieved by resetting `elapsedTime` back to 0.

# Answer
> 1 votes
Sounds like what you are looking for is Coroutines. Basically, you would write whatever code you want to execute in a function that returns `IEnumerator`, like this:

```
public IEnumerator LetsGO()
{
    elapsedTime = 0;
    float percentageComplete = elapsedTime / desiredTime;
    while(percentageComplete<1){
        transform.position = Vector3.Lerp(startPos, MoveHere, Mathf.SmoothStep(0,1, percentageComplete));
        elapsedTime += Time.deltaTime;
        yield return null;
    }
}

```

and then call this from wherever you want (in this case, I guess that would be the OnCollision callback). An important thing to note is that to start the coroutine you do not just do `LetsGo()`, but instead `StartCoroutine(LetsGo())`. There is a bit more to coroutines, and they are a very handy tool, so I would recoment giving the manual page I linked a read.

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


# Question
Title: Tangent Space View Direction based factor value remap
I'm trying to setup a mask similar to what Fresnel produces. Unfortunately Fresnel gives pretty bad results at grazing angles so I ended up using this :

```
float mask = abs(-viewDirTangentSpace.x / viewDirTangentSpace.z)

```

This gives a nice results but I would like to have values that evolves linearly. Is there a way to remap the range so it behaves like this (Photoshop) ?

# Answer
`viewDirTangentSpace.x` and `.z` form two sides of a right-angled triangle, so the `x/z` ratio you're calculating is the tangent ratio of an angle.

You can use the arctangent method to retrieve that angle in radians, in the range \\$- \frac \pi 2\\$ to \\$+\frac \pi 2\\$:

```
float angle = abs( atan(
  viewDirTangentSpace.x / viewDirTangentSpace.z
));

```

You can divide by pi and add a half to get it into the 0-1 range.
> 1 votes

---
Tags: mathematics, shaders, geometry, trigonometry
---


# Question
Title: How to reference a script that's on just one object in the same scene via code?
```
private TileMovement tileMovement;

```

As you can see in the code above I am trying to reference a `TileMovement` script, where I have some getters and setters that I want to access. I have just one instance of this script, and it's sitting on another object in the same scene.

The problem is, I don't know how to get the reference to that script instance, without doing `[Serialized Field]` or making it `public`, which I 100% don't want to do.

So how would I reference it purely with code, and no use of the editor?

# Answer
> 0 votes
If you have just one object in this scene that has a TileMovement component, you can find that unique instance like so:

```
void Start() {
    tileMovement = FindObjectOfType<TileMovement>();
}

```

This is easy to find in the docs, and in gobs of tutorials online, so be sure to do some basic searching before posting here — you'll save yourself some time by answering your own questions without having to explain your situation and wait for someone to answer.

---

When you want to do this with a component you wrote yourself, another popular method is to make it a Singleton with a static instance getter, something like:

```
public class TileMovement {
    static TileMovement _instance;
    public static TileMovement Instance => _instance;

    void Awake() {
        if (_instance != null) {
            Debug.LogWarning("Two TileMovement components in scene, but there should be only one!");
            Destroy(this);
        } else {
            _instance = this;
        }
    }
}

```

Then code can just say `TileMovement.Instance` when it wants to interact with that unique instance, without incurring any search cost, and without caching its own `tileMovement` variable.

You want to be careful with singletons, because they're mutable global state (bug risk) and lock you into only ever having one (tricky to refactor if you later find a need for multiple), but the same goes for the `FindObjectOfType` solution, so at least it's not adding *new* problems in that regard.

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


# Question
Title: Merging multiple FBX files into a single gltf
I have about 10 FBX files. Each file has a single mesh, skeleton and animation. The mesh and skeleton are the same for all files but each has a different animation.

My software can only handle gltf files so I am trying to convert from FBX to gltf.

What I want to do is grab the T pose model and fill in the geometry (i.e. vertex, normal, uv...) buffers with the T pose, fill the weight buffers with a single skeleton and then define multiple sets of animation matrices, initialized to the values in the FBX files.

I have tried doing this in blender but honestly I have very little experience with the tool as I am not an artist, just a programmer.

For example when I import the 2 models into blender I see this:

Those are 2 models each with their own animation. Since they have the same mesh and skeleton it should be trivial to just copy the animation of the second one and append it to the set of animaitons in the first one. But IDK how to achieve this.

Alternatively if there is a terminal tool or any other mechanism to do this I am fine with it. All I need is to merge the FBX files through any means as I am not going to be editing them.

Based on the most upvoted I manage to get to a state where I can cycle through all the animations in blender:

However when i export to gltf only one animation is available:

I am using this website to check my files:

https://gltf-viewer.donmccurdy.com/

# Answer
> 2 votes
In blender it's fairly easy. If you have two identical armatures, and a certain animation is only associated with one of them, like so:

You can just go to Dope Sheet -\> Action Editor

and, with the second rig selected, choose the animation from the drop-down menu.

---
Tags: animation, blender, fbx
---


# Question
Title: How do I get a directional light's (e.g. Sun's) Y axis position in a UI Widget in Unreal Engine?
I have a UI widget that will be tracking the in-game position of the sun (bottom left corner).

When I try to get the sun's position, it can't find the sun actor even though (I think) I have a reference to it in the widget blueprint.

All I get is a null reference error.

What am I doing wrong and how do I fix it?

# Answer
An event that initialize your SunActor is required. The node `GetAllActorsWithTag` has an exec pin and it required to be linked to something. For example it can be linked to the begin play event that triggers before your tick event:
> 1 votes

---
Tags: unreal-5
---


# Question
Title: Send an array of struct to compute shader
I am using Unity to send two types of data to the Compute Shader:

A struct:

```
struct Flock
{
    public Vector3 position;
    public Vector3 velocity;
}

```

And an Array of the above struct.

C# Code:

```
Flock[] ComputeFlock()
{
    Flock[] output = new Flock[Amount];

    int kernel = FlockComputeShader.FindKernel("MoveFlock");

    // Flock struct
    int size = sizeof(float) * 3 + sizeof(float) * 3;
    ComputeBuffer buffer = new ComputeBuffer(_flockAI.Length, size);
    buffer.SetData(_flockAI);

    FlockComputeShader.SetBuffer(kernel, "dataBuffer", buffer);

    // Flock array
    ComputeBuffer neighboursBuffer = new ComputeBuffer(_flockAI.Length, size * _flockAI.Length);
    neighboursBuffer.SetData(_flockAI);
    FlockComputeShader.SetBuffer(kernel, "neighbours", neighboursBuffer);

    FlockComputeShader.Dispatch(kernel, _flockAI.Length / 16, 1, 1);
    buffer.GetData(output);
    buffer.Dispose();

    return output;
}

```

Compute Shader:

```
#pragma kernel MoveFlock

struct FlockVec3Float
{
    float3 position;
    float3 velocity;
};

RWStructuredBuffer<FlockVec3Float> dataBuffer;

StructuredBuffer<FlockVec3Float> neighbours[1024];

[numthreads(16,1,1)]
void MoveFlock(uint3 id : SV_DispatchThreadID)
{
    for (uint i = 0; i < 1024; i++) {
        dataBuffer[id.x].position.xyz = dataBuffer[id.x].position.xyz + neighbours[i].position.xyz;
    }
}

```

I am trying to implemented a form of boids algorithm in the compute shader. The struct is the boid and the array of structs is to identify positions of it's neighbours. What I can't figure out is how I can send the full array of struct to the shader and have it iterate over it.

I can send the struct and have the shader read and write to it without any issues. Can someone point out what I might be doing wrong? I am wondering if it is something to do with the stride in the buffer. Thanks!

# Answer
For anyone that might have a similar question, here's how I iterate over the buffer:

uint _length;
uint _stride;

Buffer.GetDimensions(_length, _stride);

for (uint i = 0; i < _length; i++)
{
    Buffer[i];
}
```

> 0 votes

---
Tags: unity, c#, compute-shader
---


# Question
Title: How to build a system for ammunition being fired out of cannons when player characters and crewmates can also be ammunition?
I'm currently working in Unity building a game inspired by the niche DS game, Dragon Quest Rocket Slime. It's a Zelda-like forced-perspective top-down game where the primary combat mode is you physically running around on a tank to throw ammo into cannons to fire them down 'lanes', almost like a real-time card battler in the veins of the modern Clash Royale.

The problem is, I don't know how the game should handle the 'firing lanes' due to the fact that player characters and crewmates can ALSO be fired out of cannons. When they reach the other end, they'll land in the enemy ship to cause mayhem, steal ammo or sabotage their ammo dispensers.

I'm fairly rusty at programming, but my initial thoughts were creating a separate UI-element to represent the 'firing lanes' (which, in the initial DS game, was visualized through the top screen) that would use tiny sprites to simulate when ammo has reached the other side or not (and could be shot down if two opposing ammo collided), applying the relevant damage or effects upon reaching the end successfully.

The issue with that is twofold - I'm currently not sure HOW to build this system due to how many moving parts it has - defining an ammo class would be somewhat straightforward, but getting the cannon to take the ammo, spawn the ammo in the flight path with the stats the ammo has and simulate all of it, I don't quite know where to even begin as I'm still in the process of building the core movement systems and the all-important 'actual ability to pick up things and throw them into the cannons'.

The second issue is with the player characters and crewmates doubling as ammunition. I imagine I could probably make the cannons interact with the player characters differently, but the issue is how I can also apply some ammo properties to them as well in this theoretical 'the cannons turn ammo into sprites' situation. Some player characters could even have special effects when fired out of a cannon, making the difference a bit more complicated. Could I just... apply the ammo class to player characters too that activate when they're put into a cannon?

What's more is, in the original DS game, if a player character was shot down - they don't disappear like ammo, they simply fall to the ground and take some damage. Unlike the ammo, they can't be despawned so easily, and, IDEALLY, they'd also land on the ground proportional to how far they've travelled in a firing lane.

# Answer
Whenever you want to be able to do similar things with different objects, you should create a reusable component.

As an analogy, think about how you typically add physics to a GameObject. Whether that object is a crate or a beach ball or a grenade, you'll probably start by adding a Rigidbody component and some type of Collider component. The Rigidbody and Collider components don't care what they're attached to.

So, in regards to your question - you should make a reusable component that has all of the functions you need for *any* kind of ammo. Then you can attach this component to any object that can serve as ammo, whether it's a cannonball or a character or something else.

I don't know your exact needs, so here's an example that probably doesn't do exactly what you want:

```
public class CannonAmmoEvent : UnityEvent<CannonAmmo> {}
public class CannonAmmoImpactEvent : UnityEvent<CannonAmmo, Collider> {}
public class CannonAmmo : MonoBehaviour {
    [SerializeField] private ParticleSystem firedEffect;
    [SerializeField] private ParticleSystem impactEffect;
    [Min(0)]
    [SerializeField] private int damage = 10;

    [SerializeField] private CannonAmmoEvent onLoaded = new CannonAmmoEvent()
    public CannonAmmoEvent OnLoaded => onLoaded;
    [SerializeField] private CannonAmmoEvent onFired = new CannonAmmoEvent()
    public CannonAmmoEvent OnFired => onFired;
    [SerializeField] private CannonAmmoImpactEvent onImpact = new CannonAmmoImpactEvent()
    public CannonAmmoImpactEvent OnImpact => onImpact;

    public void Load() {
        onLoaded.Invoke(this);
    }

    public void Fire() {
        if (firedEffect != null) {
            Instantiate(firedEffect, transform.position, Quaternion.identity);
        }
        onFired.Invoke(this);
    }

    void OnCollisionEnter(Collision col) {
        if (impactEffect != null) {
            Instantiate(impactEffect, transform.position, Quaternion.identity);
        }
        var health = col.collider.GetComponent<Health>();
        if (health != null) health.ApplyDamage(damage);
        onImpact.Invoke(this, col.collider);
    }
}

```

Notice that I included UnityEvents that are invoked when the ammo is fired and when it impacts something. You can use these events to call code in other scripts that adds additional functionality. For example:

```
public class Character : MonoBehaviour {
    [SerializeField] private Animator animator;
    //lots of other stuff goes here
    //[...]

    //called by onLoaded event on my CannonAmmo component
    public void OnLoaded(CannonAmmo ca) {
        animator.SetTrigger("CurlIntoBall")
    }
    //called by onImpact event on my CannonAmmo component
    public void OnImpact(CannonAmmo ca, Collider collider) {
        var ship = collider.GetComponentInParent<Ship>();
        if (ship != null) {
             LandOnShip(ship);
        }
    }
    private void LandOnShip(Ship ship) {
        animator.SetTrigger("Uncurl");
        //put other appropriate logic here
    }
}

```

In some cases, you find it convenient to use inheritance - create other classes that extend `CannonAmmo` with additional/different functionality.
> 0 votes

---
Tags: unity, 2d, game-mechanics, software-engineering
---


# Question
Title: Would you ever need multiple D3D11 devices?
I'm programming a rendering engine, and I'm considering whether on not I would need to implement the availability to call `D3D11CreateDevice()` multiple times to get multiple `ID3D11Device`'s and associated `ID3D11DeviceContext`'s.

My question is whether or not one would actually ever need to get multiple Devices in the first place? Should I bother implementing the option to do so?

# Answer
For most games, a single Direct3D 11 device and single Direct3D 11 Immediate Mode Context is all you need.

You typically have multiple devices when doing DX9/DX10/DX11 interop on older versions of Windows where say Direct2D required a Direct3D 10.1 device, but you are using Direct3D 11 or if you were using DXVA which was all DirectX 9 based. See Surface sharing between Windows graphics APIs.

Otherwise the only time you'd have multiple Direct3D 11 devices is for 'heterogenous multiadapter' scenarios which are rare. For Direct3D 11, most "multi-GPU" scenarios are virtualized into one device anyhow.

> For DirectX 12, as with most other aspects, multi-adapter requires explicit support. See Microsoft Docs.
> 2 votes

---
Tags: directx, directx11
---


# Question
Title: Dynamically generating and modifying non-Euclidean/Tardis houses while maintaining AI navigability
**General Description**

I want to build a tech demo about a game concept I am carrying around for quite some time now. A lot of influences from different sources shaped this, and I will try to hint on its sources using parentheses in case some reader might want to look that up. Also, I will italic text that relates to my core concept, which together will lead to the actual question.

Imagine *up to four players*, which act as some form of state funded investigators, and a couple of *AI agents* as more or less spooky adversaries, investigating a case of missing people. They enter a *two-story* single family house with *basement*, *which looks perfectly normal from the outside*. From the inside, it should look perfectly normal too. *At first*. (The idea comes from the book House of Leaves and from the game Control)

Upon investigating the house, they should be able to find that one closet, *which extends far more than it should be*. Upon closing its door and reentering it, it will change its size and content a bit. If done long enough, *it will open up to something, that should never fit inside such a building* (yes, a bit of SCP here, and the title-giver, Dr. Who's phone both). But stays the same from the outside.

Anyway, the task would be to find somebody gone missing in there, and maybe *add a couple of AI actors* that actively try to interfere or just being plain spooky (again, SCP, but mainly Phasmophobia). *And escort them back to the outside*.

From my own gaming experience I can tell that even stuff like that can grow old fast after you learned to predict how these non-spaces do work. So that is where the *procedural generation* should come in. If the houses do look a bit alike on the inside, that is okay, but I strive to avoid using a template and only switching out parts (that is how Payday 2 handles its maps, by having certain places which rooms get switched out upon replaying).

**Core Problems so far**

* The outside must fit to the initial inside and not change during the game
* The inside must fit to the outside at the beginning
* Both should be mostly unique every play-through, with the option of using a seed to recreate these if needed (random room creation is handled here: Procedural... house with rooms generator)
* The inside should only chance if no one "is looking" (like that quantum stuff from Outer Wilds)...
* ...but if somebody is "inside" and not looking, they might disappear into an off-room or get stuck in a closet which doors lead somewhere else.
* But it must be avoided to trap the whole player squad in such a changing environment
* also, the AI actors should be able to traverse that building up to some point.... and... and... crap.

**The one question to answer?**

If you were observant, you'll have noticed that I stopped my core problems list at one point, which boils down to my core question:

-\> *How can I keep an AI actor able to traverse such a construct?*

That is not only relevant for the opposing agents, but also that person the players would need to rescue. While I could have them getting carried back to the outside by the players, it would be preferred to have them walk back to the outside behind the players.

I am aware that the "generate stuff like described and keep it playable" is a whole theme of its own, but for these aspects I do have at least a plan or something to try out first. If that fails, I still can place a new question here, for example..

But all I know about AI movement boils down to: create your level, compile a navmesh, use an algorithm of choice (mostly A\*) to make your bot move properly. But when I switch out parts of the level and the rooms inside can be bigger than the outside, I fail to imagine how to apply existing path-finding to that situation.

Even worse, as far as I remember, most of the navmesh solutions need to be done once, before the level is playable. Now it is updating mid game, possible braking running path-finding tasks because somebody closed and opened a door. I am aware that real-time updating is a thing (just any voxel and build game should do it), but they too work with normal space.

I mean, if I imagine a navmesh, it is mostly a 2D plane, that is projected onto a 3D environment from above, with coordinates in two dimensions fitting to these of the 3D space. Now I have a chunk of space, that will violate the 2D mapping in such a way, that it taps into wormhole-theory or non-Euclidean spaces.

The engine-choice or ide/framework to go with is not fixed yet, but for the sake of "use something where most of the non-programming stuff is already available to some point", I first would try to use Unity... if that matters.

# Answer
> 2 votes
Non-euclidean space is actually not as much of a problem for route finding as you would believe. The reason is that most standard route finding algorithms (A\* included) do not operate on a *grid* but on a **graph**.

A graph is a collection of nodes connected by edges which have a traversal cost. Those edges can have any cost and can connect any two nodes. That means a graph does not necessarily need to be possible in euclidean space. For example, this graph (representing a "tardis" with two entrances, a large space inside and a small space to walk around it) is perfectly possible:

So most route finding algorithms will work perfectly fine with scenarios where objects are bigger on the inside than on the outside. The heuristic function of A\* might get a bit trickier to implement in such a scenario, because the usual assumption "when it reduces the distance to the destination it's more likely to be the right way" might be less useful in a case where measuring distance is no longer a trivial problem. But that function is really just a performance optimization, so even a suboptimal heuristic function won't break your pathfinding.

Regarding changing the map layout at runtime: This always requires to change the route finding graph. Usually by swapping out the old graph section with the new one. This invalidates all paths going through the swapped out graph, so they need to be recalculated. It might in some cases also be prudent to recalculate any other paths, because there might now be a shorter option through the new graph section.

# Answer
> 2 votes
Since you're working with houses, you can leverage the conventions of those structures to simplify the problem.

To a first approximation, a house is a collection of rooms connected by doorways and windows. We can model that as a graph, where each room is a node, and each doorway or window that might allow line of sight or traversal between rooms is an edge. The outdoors is one "root" room, onto which any exterior doors/windows connect (at least initially - maybe later you add a door that exits to a different exterior world...)

This gives you a graph that you can use directly for AI pathfinding. It does not matter whether the connections between those rooms defies any possible embedding in 3D Euclidean space: as long as you have a graph of connections, A\* can find connected paths through that graph. Working at the granularity of rooms will also make these searches *fast*, since you probably only have on the order of dozens of rooms at a time with a handful of doors each, so searching the entire graph can be done quickly, and does not depend on the amount of area they occupy.

You can make your AI pathfinding easier if all rooms have a convex floor plan, and any obstacles are small. Then you don't need a navmesh at all: to traverse a room from wherever you happen to be to any possible exit is just a straight line path, with local avoidance sufficing to walk around a table or chair in the way. You can still have non-convex rooms by splitting them into multiple convex parts, treating the seam between them as if it were just a large doorway. This also makes it easier to change the unoccupied part of a room hidden behind a concave bend, because it's logically a separate piece from the occupied portion.

(If you need more complicated pathfinding within rooms, you can still use separate navmesh islands for each one, without concern whether they overlap/link up in 3D space. As long as an agent can navigate to Door A in Room X using Room X's navmesh, you can then teleport them to the matching Door B in Room Y, and they can continue their navigation in that room using Room Y's navmesh, even if there's no way the two could coexist in one space)

Within each room, space is Euclidean, and you can use frustum checks to test which open doors or windows are within the field of view of any agent. Any which are not can then be flagged as candidates for modifying the house unseen - deleting them, or re-linking them to a matching portal somewhere else. You can do a similar thing with blank patches of wall - any that are unobserved can become candidate locations for a new edge to attach.

Each time you perform one of these modifications, invalidate any active AI navigation paths that used one of the modified edges. Then run a new A\* search from that agent to the original "outside" room. If the search fails, your last modification has stranded this agent in an island with no traversible connections back to the outside, and you can simply undo the modification. Try another one next frame. You can run a similar search from each player position to avoid trapping players, or detecting when a player has become trapped if you want to let it happen for a little while, before offering a chance at salvation.

You can also run a connected component search to identify any rooms that have become unreachable/invisible from any reachable room, and prune them to save resources, freeing up budget for new rooms.

---
Tags: procedural-generation, path-finding, navmesh, non-euclidean
---


# Question
Title: How do I edit an outdated SKSE plugin for Skyrim LE?
I am attempting to confirm whether an SKSE plugin file in .dll format can be re-opened, edited, and recompiled to work with the latest SKSE.

My attempts thus far, as guided by the Nexus and other Skyrim modding forums, have all failed to produce editable code, much less an updated SKSE plugin.

I understand that to open the .dll as a C++/C# project, it requires an installation of Visual Studio, as well as the 2015 toolset.

I am asking here so I can get a baseline understanding of what editing .dll files requires, and more particularly how to do so when the .dll is intended for use in an SKSE mod.

I know this is a little broad, but I am honestly a bit confused where to begin, even as a programmer with past experience in C based languages. I've just never worked with .dll files before.

So far I have tried using VS2019 to open the old .dll plugin I want to update with the correct toolset installed, yet the file did not seem to be editable or possible to compile, even with the old VS install I hunted to find a legitimate download for. The file just seems, well, empty.

Any suggestions where to start are appreciated. I have searched high and low on the internet, but have found little on the subject that is targeted at what I am attempting to do, and what is seems outdated or for SSE instead of Skyrim LE.

Thanks in advance!

# Answer
> 3 votes
DLL files have been compiled into a format that your CPU can directly execute. Since Legendary Edition is a 32-bit app, that format is probably x86-32 machine code (along with some extra junk that tells Windows how to load the DLL into a program's address space). But regardless of your architecture, it is certainly not C. You can't usefully open a DLL in Visual Studio, or any IDE. You would need to decompile it, which will likely produce extremely messy and difficult to understand source code, or ask the author for the original source code, and then recompile against SKSE64.

# Answer
> 0 votes
By the way, you can edit DLL even if sources are not available. The process is called "reverse engineering" and it could be accomplished by rookie if not major altering of original DLL required.

The worst scenario is that DLL is protected against reverse engineering. But in that case you still can try to find reverse engineer and give him that task - every binary can be modified, it is just the matter of time.

---
Tags: pc, skyrim-modding
---


# Question
Title: Any way to copy data into a component in another thread?
Pretty sure the answer to this is a resounding no but just in case...

Running an expensive algorithm in a separate thread. However, it returns data that must be copied into the arrays of a Shapes.Polyline (plugin takes an array of custom point objects), and into the Vector2 array of an edge collider.

Still a noticeable dip in framerate as it copies the data into those collections (it's a lot of vectors).

Is there any way at all to do those last steps in a separate thread?

Or will I have to use a coroutine to spread it over several frames?

# Answer
> 2 votes
It's probably not the copying that's taking the time, but the updating of the rendered polygons and collision detection acceleration structures in response to the newly-copied data.

Since those operations are changing the state of data that's in use every frame to step the simulation and render the result, it can't be done in parallel with those activities. You need to do it on the main thread in between simulation steps / renders.

You can probably reduce or eliminate the noticeable hitch by splitting the work into smaller parts - say making n polylines that join end-to-end to create the same look as one continuous polyline. Then you can update one of those n segments in a frame, and update the next segment next frame, so no single frame has to bear the burden of recalculating all of the rendered and collision geometry.

---
Tags: unity, multithreading
---


# Question
Title: What is the function or benefit of including juggling mechanics in a fighting game?
I am putting together the initial design ideas for a 3D fighting game. Overall the style of the combat I would like to be something between UFC and DOA games, so focused on realism but the pacing more like cinema combat.

After doing research on the most successful fighting games I have found that the juggle mechanic seems to be common amongst many of them. Honestly I can't really understand why this is so popular for the following reasons:

1. From a fighting perspective it is quite a ridiculous idea and does not happen in any real fighting style competition. You might knock a person of their feet, very rarely hit them once when they are in the air but to do some kind of combo or base a winning strategy around it, no way.
2. As a game mechanic I find the idea of having a player wait without being able to do anything while they are being juggled in the air seems not very fun, especially if the damage potential is very high eg. half the player health. It also feels unnecessarily punishing in that one mistake can end the match, although in real fighting competition it is also the case that a single attack can end a match as well.

I am wondering what it is about this mechanic that is so beneficial in fighting games? Because to all honesty I was thinking of not using it at all but I'm not sure if that means I have to compensate for it in my design somehow to keep the game balanced? I know some games like Tekken experimented with their juggle feature such as adding characters that could escape juggles or severely toning them done like in Tekken 4.

I was thinking of perhaps using something like a stun system instead, where certain attacks will stun the other player allowing a free hit but perhaps still giving the stunned player an option such as a counter/reversal so they are not just stuck waiting there. This would reward players with similar free hit combos if they executed a stun combo and I am thinking of possibly adding some kind of escape move at certain points in the combo to allow the player being damaged opportunities to turn the tables. I am wondering though if both the counter/reversal and stun escapes tip the balance too far into the player being damaged side, making it not worth the effort for the attacking player? How exactly do I find a balance for this? Because I don't want the game to be only a defensive game, where the player who waits longer and counters will always have the advantage. For example, if the juggle mechanic was completely removed from a game like Tekken or DOA, would something else in the game need to change to compensate? I feel it would just make them a bit more like UFC games, but happy to get other explanations on this.

# Answer
> 15 votes
Indie fighting game developer chiming in, with one released low poly 3D fighting game. The following answer is based on my personal experience and what I observed in the genre.

## Juggle systems in general

Juggle systems in 3D fighters are mostly the counterpart to grounded link combos in 2D fighters. What they do is **guarantee some measure of damage out of winning a gameplay interaction.**

Games like Tekken, Dead or Alive and Virtua Fighter use them to allow a player that scored one hit to actually get some reward out of it. **It's a reward for opening up the opponent** and it's considered fairly intuitive from a gameplay stand-point (you launch the opponent in the air and hit them until they fall down) compared with traditional 2D links (in which you need to know which move will be fast enough to keep your grounded combo going on after the first hit is capitalized).

In short, the pros of juggling systems are:

1. Somehow intuitive for casual players compared to traditional grounded combos, as once the opponent is in the air they can experiment freely with hitting them;
2. At the same time, more competitive players have a lot of room for optimization and finding how to dish out the most damage out of a specific launcher, increasing the depth of the combo system
3. Give a damage reward to a player that managed to outsmart their opponent, not unlike a traditional combo

It's perfectly fair not to like juggles (I too do think some games go too far with them), but once you see them as an equivalent to an unexcapable grounded combo - only, in the air - you can see that they aren't too different in concept from what is a staple in the genre.

## What would happen if you remove juggles?

Removing the juggle system in the games you mentioned **would be akin to removing most of the high damage combos from those games**, making them have more weight on neutral and more room for errors and mistakes from both players. Current iterations of DoA and Tekken are games that can be decided in 3-4 interactions. Removing juggles, you would have a game more focused on neutral back and forth, with matches that would potentially last longer.

It's a direction you are free to take, it's just not the direction the games you mentioned chose - and it's perfectly fine.

## Notable 3D fighting games with limited juggle systems

Virtua Fighter and Soulcalibur have some limited juggles that don't last long and are used as a way to dish out more damage, capitalising on an opponent's error. Virtua Fighter is in general a game with high damage per se, so even without juggles rounds don't last long. In my experience, Soulcalibur tends to be more focused on neutral than on combos and the limited juggles and air evasion system might be something you want to look into. Both games aren't supposed to be realistic, though.

In the end, juggles are just a tool in your fighting game development toolbox - **if you don't find them useful for your game, you are not forced to use them.**

## Conclusions

### Edited in on 28.06.22 to incorporate a discussion in the comments

In the end, whether one has juggles, links or stun-based combos in their game, **all those mechanics are stand-ins for giving a player who successfully scored a hit some measure or reward for winning the interaction.**

As long as you can give an attacking player some benefit from managing to hit the opponent with a high risk move (a launcher, a slow, heavy normal or anything similar), you can *functionally* replace one with the other.

Of course, the execution requirements will be different (with e.g. juggles being averagely easier for a new player than links), so you will have to juggle (no pun intended) the various component in your system until you obtain the result you want to achieve.

# Answer
> 13 votes
Juggling is one of the mechanic that experts in fighting games usually expect to have. It offers a chance to avoid it to the receiving player. And it offers potentially high punishment, bound to the skill of the attacker.

When I say punishment, I mean, of course, that to juggle the move should be clear and easy to avoid… Why would the other player not do so? It could be because they didn't know, or didn't notice, or because they were in an animation. Which could be an attack with long recovery animation that didn't connect (and is being punished), or… you know… they are falling… perhaps because they are being juggled.

So, yes, they are NOT beginner friendly. Ultimately it is prevalent in fighting games because those games target expert players. *And if that is the audience you want, then consider including it too.*

---

Perhaps you are making a more beginner friendly fighting game. In which case, I would suggest the exercise of design by elimination. Look that mechanics, see what does not fit, and don't include that. Under this approach, making a fighting game without juggling makes perfect sense.

---

But are you making a fighting game? What I'll say might sound like splitting hairs. But the line between genres can be fussy. For this answer, consider genres to be clusters of mechanically challenge and aesthetics given a name by marketing.

You have been searching for fighting games, and you are finding these games with juggling. So marketing says fighting games have juggling. If your game does not have juggling, perhaps it isn't a fighting games. *There is no shame on that.*

What I'm suggesting is that thinking that you are making a fighting game is not helping you. In fact, it seems to me that "wrestling game" is a better match (I might be wrong on that). If you look at wrestling games, you are going to see more realistic combat, with virtually no juggling.

You can think about the target audience of your game, and consider the game genre they want and their level of mastery of that genre, and try to make a game that fits that… Or you can make the game you want, with the mechanics you want, and then see where it fits. *And it might end up fitting somewhere you didn't expect.* And perhaps you find that your game fits a particular genre, and then take as reference other games in that genre.

So look at wrestling games and other adjacent genres. It might be simply that you are taking the wrong references.

Addendum: You should also contrast the 2D and 3D variants of these genres.

# Answer
> 3 votes
I've contemplated this question myself while my character is floating unrealistically in midair, getting beat to a pulp while I wait to be able to play the game again, which often isn't clear to a new player.

They do actually simulate something real though. If you are inexperienced and your opponent gives you an opening, you hit them with some kick and do maybe 10% of their health. If you are experienced, you hit them with a launcher you've practiced a hundred times and do maybe half their health. This is realistic, if you open yourself up to someone who has practiced a kick hundreds of times you are in trouble.

What juggling does is reward practice and being cool under pressure (you have to hit that combo you've been practicing in a live fight, maybe even a tournament). You can easily tune damage so a juggleless game ends just as kickly as one with juggling, but what you'd lose is that differentiation between the noob and the person who's practiced the kick hundreds of times.

Maybe it's fine for your game to not have that, but I think if you come up with a way to have really technically difficult to perform, high damage attacks that don't prevent the opponent from playing the game while they defy gravity, that would be amazing.

Good luck!

# Answer
> 1 votes
In a fighting game, as well as most games in general, you want to reward some type of actions compared to other types. So, then, what do juggles, here considered to be any type of inescapable combos, reward?

First, it's important to compare equally. Say a strong punch turns into a juggle. The proper comparison isn't with the same punch simply not allowing a juggle, but with that punch not allowing the juggle, but instead being as powerful as the juggle. So what does this reward?

It rewards research-type preparation. Knowing in advance how combos work, what combos work with what, how to achieve ideal combos.

It rewards 'thoughtless' execution. Being able to input a specific, already known series of commands with the correct timing.

It can reward ability to react to initial conditions, if the ideal juggle differs depending on exact character placements or even initial momentum.

Detrimentally, juggles in general will make your game more difficult to balance. Unless you know every single combo, the balance of your entire game can depend on the discovery of a powerful juggle starting from what you had believed to be a weak move.

Juggles can also dramatically widen the gap between players of different skills. The punch of a player who can't juggle will be, essentially, weaker than the punch of a player who can. Whether you consider that an advantage or a detriment is to your discretion.

---
Tags: game-design, game-mechanics, balance, fighting-game
---


# Question
Title: Scope of 'this' - Cannot read property of undefined in collider and overlap function
I am working on my first 2D game with Phaser 3. I have set up VS Code with a node.js https server and run it to deploy the game on localhost.

While the game gets compiled successfully and deployed, I get a runtime error when executing the collider and overlap function:

> Uncaught TypeError: Cannot read property 'isParent' of undefined
> at World.collideObjects (phaser.js?d4ef:102761)
> ...

For the time being I have a title screen with "welcome to my game" text and it is clickable. Once you click that you are navigating to the play scene. When navigating to the play scene, I am getting that error displayed as you can see here:

I suspect that this is caused by my use of the `this` keyword and the scope of it. But I have no idea how to fix that. I spent 2-3 hours debugging and playing with 'this.' here and there but I am still clueless as to how I can fix this and what I did wrong.

The comment `//Error on "is parent undefined"` is added to mark the lines where I get the error.

```
import Phaser from 'phaser';

class PlayScene extends Phaser.Scene {

constructor() {
    super('PlayScene');
}

create() {
    var player;
    var stars;
    var bombs;
    var bomb;
    var platforms;
    var cursors;
    var score = 0;
    var gameOver = false;
    var gameOverText;
    var scoreText;
    var leftKey;
    var rightKey;
    var upKey;
    var repeatStarCount;
    this.add.image(400, 300, 'sky');

    platforms = this.physics.add.staticGroup();
    platforms.create(390, 568, 'ground1');

    platforms.create(750, 200, 'ground2');
    platforms.create(0, 150, 'ground4');
    platforms.create(690, 420, 'ground4');
    platforms.create(100, 320, 'ground4');

    player = this.physics.add.sprite(100, 450, 'dude');
    player.setBounce(0.2);
    player.setCollideWorldBounds(true);
    player.setScale(0.15);
    player.setSize(300, 400, false);
    player.body.offset.y = 0;
    player.body.offset.x = 0;

    //  Input Events
    this.cursors = this.input.keyboard.createCursorKeys();
    this.leftKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT);
    this.rightKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT);
    this.upKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP);

    //  player animations
    this.anims.create({
        key: 'LeftRun',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 14,
            end: 17
        }),
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'LeftJump',
        frames: [{
            key: 'dude',
            frame: 13
        }],
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'LeftIdle',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 9,
            end: 10
        }),
        frameRate: 10,
        repeat: -1
    });
    this.anims.create({
        key: 'LeftDizzy',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 10,
            end: 11
        }),
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'RightRun',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 5,
            end: 8
        }),
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'RightJump',
        frames: [{
            key: 'dude',
            frame: 4
        }],
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'RightIdle',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 0,
            end: 1
        }),
        frameRate: 10,
        repeat: -1
    });

    this.anims.create({
        key: 'RighttDizzy',
        frames: this.anims.generateFrameNumbers('dude', {
            start: 2,
            end: 3
        }),
        frameRate: 10,
        repeat: -1
    });

    //  Some stars to collect, 12 in total, evenly spaced 70 pixels apart along the x axis
    repeatStarCount = 10;
    this.stars = this.physics.add.group({
        key: 'star',
        repeat: repeatStarCount,
        setXY: {
            x: 8,
            y: 0,
            stepX: 50
        },
        setScale: {
            x: 0.05,
            y: 0.05
        }
    });

    this.stars.children.iterate(function(child) {

        child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));

    });

    this.bombs = this.physics.add.group();

    var style = {
        font: "30px Arial",
        fill: "#ffff00",
        stroke: "#535353",
        align: "center",
        strokeThickness: 15,
    };

    var style1 = {
        font: "40px Arial",
        fill: "#ffff00",
        stroke: "#535353",
        align: "center",
        strokeThickness: 15,
    };

    scoreText = this.add.text(0, 0, "Score: 0", style);
    gameOverText = this.add.text(300, 250, "Game Over", style1);
    gameOverText.visible = false;

    //  Collide the player and the stars with the platforms
    this.physics.add.collider(player, platforms);
    this.physics.add.collider(stars, platforms);
    this.physics.add.collider(bombs, platforms);

    //Error on "is parent undefined"
    this.physics.add.overlap(player, stars, () => {

        star.disableBody(true, true);

        //  Add and update the score
        score += 10;
        scoreText.setText('Score: ' + score);

        if (stars.countActive(true) === 0) {
            repeatStarCount = +3;
            //  A new batch of stars to collect
            stars.children.iterate(function(child) {

                child.enableBody(true, child.x, 0, true, true);

            });

            var x = (player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);

            var bomb = bombs.create(x, 16, 'bomb');
            bomb.setBounce(1);
            bomb.setCollideWorldBounds(true);
            bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
            bomb.allowGravity = false;

        }

    }, null, this);

   //Error on "is parent undefined"
    this.physics.add.collider(player, bombs, () => {
        this.physics.pause();
        if (player.anims.currentAnim.key === 'RightRun' || player.anims.currentAnim.key === 'RightIdle' || player.anims.currentAnim.key === 'RightJump') {
            player.anims.play('RighttDizzy');
        }

        if (player.anims.currentAnim.key === 'LeftRun' || player.anims.currentAnim.key === 'LeftIdle' || player.anims.currentAnim.key === 'LeftJump') {
            player.anims.play('LeftDizzy');
        }
        gameOver = true;
        let timer = this.time.delayedCall(500, () => {
            player.anims.stop();
            gameOverText.visible = true;
        }, [], this);
    }, null, this);
}

update() {
    if (this.gameOver) {
        return;
    }

    if (this.cursors.left.isDown) {

        player.setVelocityX(-160);
        player.anims.play('LeftRun', true);

    } else if (this.cursors.right.isDown) {

        player.setVelocityX(160);
        player.anims.play('RightRun', true);

    } else if (Phaser.Input.Keyboard.JustUp(this.leftKey)) {

        player.setVelocityX(0);
        player.anims.play('LeftIdle', true);

    } else if (Phaser.Input.Keyboard.JustUp(this.rightKey)) {

        player.setVelocityX(0);
        player.anims.play('RightIdle', true);

    } else if (Phaser.Input.Keyboard.JustUp(this.upKey) && player.anims.currentAnim != null) {

        if (player.anims.currentAnim.key === 'LeftJump') {
            player.anims.play('LeftIdle', true);
        }

        if (player.anims.currentAnim.key === 'RightJump') {
            player.anims.play('RightIdle', true);

        }

    } else if (this.cursors.up.isDown && player.anims.currentAnim != null) {

        if (player.anims.currentAnim.key === 'RightIdle') {
            player.anims.play('RightJump', true);
            if (player.body.touching.down) {
                player.setVelocityY(-350);
            }
        }

        if (player.anims.currentAnim.key === 'LeftIdle') {
            player.anims.play('LeftJump', true);
            if (player.body.touching.down) {
                player.setVelocityY(-350);
            }
        }
    }
}}export default PlayScene;

```

# Answer
I solved this problem. The issue is actually related to variable declaration. So I moved all the variable declarations in to the constructor and that fixed the problem. I don't know whether that is a common practice or not anyway.
> 1 votes

# Answer
You mentioned you were able to get it working, but here's more context.

`this` contains all the properties of the class that you're accessing `this` from. As you can see, all your code is within the definition of the `PlayScene` class that extends `Phaser.Scene`. Class properties are declared in the class, outside of any function, e.g.:

```
class PlayScene extends Phaser.Scene {
    classProp = 5;

    constructor() {
        super('PlayScene');
    }
    //... more code
}

```

In the above case, `classProp` is accessed via this: `this.classProp`.

In your code, you attempt to access some variables such as `stars` using `this`, when you decarded them as local variables to the create function. That means `stars` is only available to `create()` and is accessed directly, without using `this`.

Now here's the tricky part. You can still set `this.stars` even if you never declared it. `this.stars = 5;` is valid, and the next time you access `this.stars`, you will get 5 instead of `undefined`. But, if you declare `var stars;` and then set `this.stars = 5`, these are two different variables! So when you access `stars` without `this`, you will get `undefined`. An example:

```
class Scene {
  constructor() {}

  create() {
    let stars;

    this.stars = 5;

    console.log(`stars: ${stars}`);
    console.log(`this.stars: ${this.stars}`);
  }

}

const scene = new Scene()
scene.create();

```

So, on these lines:

```
//Error on "is parent undefined"
this.physics.add.overlap(player, stars, () => {

```

You accessed stars, the local variable you declared. But when you actually created stars, you did so like this:

```
this.stars = this.physics.add.group({
// ...

```

`stars` is undefined, while `this.stars` points to the object you created.

I hope all of that helps!

For further information, I use TypeScript instead of JavaScript to avoid making mistakes like this, as TypeScript uses a typing system that wouldn't allow me to assign to a variable I haven't explicitly declared yet.
> 0 votes

---
Tags: javascript, phaser, collider
---


# Question
Title: How to detect unknown forces on pool re-used rigidbody?
I have a ragdoll which performs dying quite well when it is initialized. But when the same prefab object is re-used by being pooled and recycled, it jerks violently when die. As if some forces were left on the rigidbodies when the mesh is disabled.

My code goes through the rigidbodies in the ragdoll and sets isKinematic when the enemy is alive and does his usual animations, but turns isKinematic false when the enemy dies so that ragdoll can take over. From there the pool's lifetime kicks in giving the corpse sometime to be a ragdoll, then the whole gameobject is disabled and pooled. When a new enemy is to generated the pool is asked for one and it is provided. The enemy enters the game normally and performs it's animations correctly. This is where the problem occurs, when the enemy is killed a second time it "jerks" upward as if collapsing in on itself.

The only thing I could think of it that there are some forces left on the mesh when disabled and they activate again when the ragdoll is enabled through death. So I went through all rigidbodies and do:

```
rigidbody.angularVelocity = Vector3.zero;
rigidbody.velocity = Vector3.zero;

```

But this doesn't also work, so I'm not sure if it's remnant forces or even if there's such a thing.

What else could be effecting the gameobject to cause a sudden jerk in the ragdoll, which supposedly doesn't have any forces applied on it's inception?

# Answer
Pooled objects are carrying velocity after disabled. I solved the issue by setting velocity to zero and `WaitForFixedUpdate` to handle physics and then disable the object and set it to pool. So when you call the object and enable it, velocity will be 0. Code below may help:

Use below line where you want to disable the obj:

```
StartCoroutine(ResetRigidbodyAndDisable());

```

and the coroutine below:

```
IEnumerator ResetRigidbodyAndDisable()
{
     if (rb != null)
     {
         rb.velocity = Vector3.zero;
         rb.angularVelocity = Vector3.zero;
     }
     else
     {
         rb = GetComponent<Rigidbody>();
         rb.velocity = Vector3.zero;
         rb.angularVelocity = Vector3.zero;
     }

     yield return new WaitForFixedUpdate();
     gameObject.SetActive(false);
 }

```
> 1 votes

# Answer
You do have to be careful to run

```
rigidbody.angularVelocity = Vector3.zero;
rigidbody.velocity = Vector3.zero;

```

when re-using RigidBodies from a pool. You haven't shared the full code you use to reset the `velocity`/`angularVelocity` for each Rigidbody, so it's possible there's a typo in your code. For example, this would not work as intended:

```
Rigidbody rigidbody = GetComponent<Rigidbody>();

Rigidbody[] childRigidBodies = GetComponentsInChildren<Rigidbody>();
foreach (var child in childRigidBodies) {
    rigidbody.velocity = Vector3.zero; //wrong reference!
    rigidbody.angularVelocity = Vector3.zero; //wrong reference!
}

```

Double-check that your code is actually reaching all of the Rigidbodies and resetting their velocities correctly. One easy way to check this is to apply some silly value that will be vary obvious:

```
Vector3 crazyVelocity = new Vector3(1000, 0, 0);
Rigidbody[] childRigidBodies = GetComponentsInChildren<Rigidbody>();
foreach (var child in childRigidBodies) {
    child.velocity = crazyVelocity;
    child.angularVelocity = Vector3.zero;
}

```

If your bodies go shooting off along the x-axis, you know that your code is reaching all of them. If not, then there's probably a mistake in your code.
> 1 votes

---
Tags: unity, rigidbody, rigid-body-dynamics
---


# Question
Title: Model path of bullet to hit future position of balloon
I am coding a Bloons Tower Defense Game and one of the problems I have is how to shoot a projectile from a tower and have it hit a balloon that is moving along a certain path. The way I am currently moving my balloon is by having a list(length approximately 15) which stores different pixels the balloon has to reach(which essentially defines its path). Then for every frame I calculated the difference in x and y for the pixel I am currently on in the list and the pixel in the next index. I use some trig to add to then change the x and y position of the balloon to reach closer to the next pixel in the list. The method is shown here:

```
    def move(self):
        x1, y1 = self.path[self.path_index]
        x2, y2 = self.path[self.path_index + 1]

        changex = x2 - x1
        changey = y2 - y1
        angle = math.atan2(changey, changex)

        self.x += math.cos(angle) * self.velocity
        self.y += math.sin(angle) * self.velocity

        if round(self.x) == x2 and round(self.y) == y2:
            self.path_index += 1

```

If the balloon was traveling in a straight line it would be super easy to shoot a bullet such that it hits the balloon, however, the path has several turns and curves, and I am not sure how to create some method which sends the bullet in a certain direction such that the bullet hits the balloon no matter what. Im guessing I have to do some future balloon position predictions in code but that seems inefficient and I am not really sure if that will even work so any help is greatly appreciated.

# Answer
If I understand correctly, the targets move along a path defined as a series of points. So, effectively, it is moving along a series of straight segments, correct?

Thus, you could:

1. Solve the time and position for the collision along the current segment.
2. Check if that position is beyond the end of the segment.
3. If it is, add a time offset for the time to reach the end of the segment, take the next segment as current, and repeat from step 1.
4. If you still have not found a viable interception after considering the last path segment, then you cannot intercept this target. Try a different target, wait, or shoot to miss.

Makes sense?

---

Ok, we have:

* The shooter position. I'll call it `s_pos`.
* The bullet speed. I'll call it `b_speed`.
* The target initial position. I'll call it `t_pos_0`.
* The target velocity. I'll call it `t_vel`.
* The time offset. I'll call it `time_0`.

And we want:

* Collision time.
* Collision position.

We know that the distance the bullet would have traveled in function of time is:

```
b_travel_dist(time) = b_speed * time_0 + b_speed * time

```

I'll take the first terms to be computed before hand:

```
b_travel_dist_0 = b_speed * time_0

```

And now we have:

```
b_travel_dist(time) = b_travel_dist_0 + b_speed * time

```

If we can find the function of the distance of the target to the shooter in terms of time, the point where these functions cross is the solution.

We can start with the position of the target as a function of time:

```
t_pos(time) = t_pos_0 + t_vel * time

```

And then the offset between target and shooter as a function of time:

```
ts_offset(time) = t_pos(time) - s_pos

```

And then their distance:

```
ts_dist(time) = length(ts_offset(time))

```

So we can equate the distance between target and shooter and the distance the bullet traveled:

```
ts_dist(time) = b_travel_dist(time)

```

Replacing:

```
length(t_pos_0 + t_vel * time - s_pos) = b_travel_dist_0 + b_speed * time

```

Actually, I want to reorganize it so that the terms that do not have time are together:

```
length(t_pos_0 - s_pos + t_vel * time) = b_speed * time

```

In fact, you can take those to compute beforehand too:

```
ts_offset_0 = t_pos_0 - s_pos

```

And we have a little less cognitive load:

```
length(ts_offset_0 + t_vel * time) = b_travel_dist_0 + b_speed * time

```

And then we solve for time (we of course know the time must be positive)… Hmm…

Look, we can divide by time on both sides (take your time to think it through):

```
length(ts_offset_0/time + t_vel) = b_travel_dist_0/time + b_speed

```

Ok, let us separate the x and y components:

```
sqrt
(
    (ts_offset_0.x/time + t_vel.x)^2
    +
    (ts_offset_0.y/time + t_vel.y)^2
)
=
b_travel_dist_0/time + b_speed

```

So we can square both sides:

```
(ts_offset_0.x/time + t_vel.x)^2
+
(ts_offset_0.y/time + t_vel.y)^2
=
(b_travel_dist_0/time + b_speed)^2

```

Let us expand those:

```
(ts_offset_0.x/time)^2 + 2*(ts_offset_0.x/time)(t_vel.x) + (t_vel.x)^2
+
(ts_offset_0.y/time)^2 + 2*(ts_offset_0.y/time)(t_vel.y) + (t_vel.y)^2
=
(b_travel_dist_0/time)^2 + 2*(b_travel_dist_0/time)(b_speed) + (b_speed)^2

```

Reorganize:

```
  (ts_offset_0.x/time)^2
+ (ts_offset_0.y/time)^2
+ 2*(ts_offset_0.x/time)(t_vel.x)
+ 2*(ts_offset_0.y/time)(t_vel.y)
+ (t_vel.x)^2
+ (t_vel.y)^2
=
  (b_travel_dist_0/time)^2
+ 2*(b_travel_dist_0/time)(b_speed)
+ (b_speed)^2

```

Reorganize harder:

```
  (ts_offset_0.x)^2/time^2
+ (ts_offset_0.y)^2/time^2
+ 2*(ts_offset_0.x)(t_vel.x)/time
+ 2*(ts_offset_0.y)(t_vel.y)/time
+ (t_vel.x)^2
+ (t_vel.y)^2
=
  (b_travel_dist_0)^2/time^2
+ 2*(b_travel_dist_0)(b_speed)/time
+ (b_speed)^2

```

Reorganize harder:

```
  ((ts_offset_0.x)^2 + (ts_offset_0.y)^2)/time^2
+ (2*(ts_offset_0.x)(t_vel.x) + 2*(ts_offset_0.y)(t_vel.y))/time
+ (t_vel.x)^2 + (t_vel.y)^2
=
  (b_travel_dist_0)^2/time^2
+ 2*(b_travel_dist_0)(b_speed)/time
+ (b_speed)^2

```

Let us multiply everything by time squared:

```
  (ts_offset_0.x)^2 + (ts_offset_0.y)^2
+ time * (2*(ts_offset_0.x)(t_vel.x) + 2*(ts_offset_0.y)(t_vel.y))
+ time^2 * (t_vel.x)^2 + (t_vel.y)^2
=
  (b_travel_dist_0)^2
+ time * 2*(b_travel_dist_0)(b_speed)
+ time^2 * (b_speed)^2

```

Reorganize again:

```
  time^2 * (t_vel.x)^2 + (t_vel.y)^2
+ time * (2*(ts_offset_0.x)(t_vel.x) + 2*(ts_offset_0.y)(t_vel.y))
+ (ts_offset_0.x)^2 + (ts_offset_0.y)^2
=
  time^2 * (b_speed)^2
+ time * 2*(b_travel_dist_0)(b_speed)
+ (b_travel_dist_0)^2

```

Ah, a quadratic equation in canonical form:

```
  time^2 * ((t_vel.x)^2 + (t_vel.y)^2 - (b_speed)^2)
+ time * ((2*(ts_offset_0.x)(t_vel.x) + 2*(ts_offset_0.y)(t_vel.y)) - 2*(b_travel_dist_0)(b_speed))
+ (ts_offset_0.x)^2 + (ts_offset_0.y)^2 - (b_travel_dist_0)^2
=
0

```

Let us take the parts out:

```
a = (t_vel.x)^2 + (t_vel.y)^2 - (b_speed)^2
b = (2*(ts_offset_0.x)(t_vel.x) + 2*(ts_offset_0.y)(t_vel.y)) - 2*(b_travel_dist_0)(b_speed)
c = (ts_offset_0.x)^2 + (ts_offset_0.y)^2 - (b_travel_dist_0)^2

```

Wait, I want to write those another way:

```
a = t_vel.dot(t_vel) - b_speed * b_speed
b = 2 * ts_offset_0.dot(t_vel) - 2 * b_travel_dist_0 * b_speed
c = ts_offset_0.dot(ts_offset_0) - b_travel_dist_0 * b_travel_dist_0

```

And we have:

```
a * time^2 + b * time + c = 0

```

Let us cut to it, and use the quadratic formula. We have two solutions:

```
time = (-b + sqrt(b^2 - 4ac))/2a

```

And

```
time = (-b - sqrt(b^2 - 4ac))/2a

```

We want the smaller positive one.

---

To recap we compute these beforehand:

```
b_travel_dist_0 = b_speed * time_0
ts_offset_0 = t_pos_0 - s_pos

```

Then these:

```
a = t_vel.dot(t_vel) - b_speed * b_speed
b = 2 * ts_offset_0.dot(t_vel) - 2 * b_travel_dist_0 * b_speed
c = ts_offset_0.dot(ts_offset_0) - b_travel_dist_0 * b_travel_dist_0

```

And finally these:

```
times = [
    (-b + sqrt(b^2 - 4ac))/2a,
    (-b - sqrt(b^2 - 4ac))/2a
]

```

That is, of course, riddled with pitfalls. Namely division by zero and square root of negative numbers.

That is because we are looking for a solution when the shooter shoots at time zero. So the solution is simple: if computing this is invalid… Don't shoot. Skip the segment. If you reach the end of the path, check again next frame.

To ease computing the times, I'll do this instead:

```
bb = b * b
a2 = 2 * a
ac4 = 4 * a * c

```

And then we can do this:

```
if bb >= ac4:
    r = sqrt(bb - ac4)
    times = [
        (-b + r)/a2,
        (-b - r)/a2
    ]

```

Let us find if there is a valid time:

```
    time = INF
    for candidate_time in times:
        if candidate_time < 0.0:
            continue

        if candidate_time < time:
            time = candidate_time

    if not is_inf(time):
        pass

```

You can compute the point to aim simply like this:

```
t_pos_0 + t_vel * time

```

---

Alright, but we need to check if it is within this segment, otherwise we have to loop, right? right. So we do something like this:

```
t_index = index
while t_index + 1 < t_points.size():
    next_point = t_points[t_index + 1]
    t_vel = (next_point - t_pos_0).normalized() * t_speed
    time_to_next_point = (next_point - t_pos_0).length() / t_speed

    # OTHER STUFF SHOWN BEFORE GOES HERE

    if not is_inf(time):
        if time <= time_to_next_point:
            # INSERT SHOOT CODE HERE
            return

    time_0 += time_to_next_point
    t_pos_0 = next_point
    t_index += 1

```

Yes, I have tested this. *In Godot with GDScript. Which is what I have been writing here in the last parts of the answer. It is not Python, but it has very similar syntax. So I hope it is not hard to adapt.*
> 2 votes

---
Tags: physics, python, projectile-physics, tower-defense
---


# Question
Title: How to handle duplicate logic in a state machine for a platformer player?
I'm trying to implement a platformer character using a finite state machine, but I have troubles understanding what kind of logic goes into a state and what logic goes into a main player class directly.

I have a base state class and a couple of state classes that implement it, like Idle, Running, Jumping state etc. Every state has an `update` method. The player class has a member `state_machine` that handles transitioning states and other state related things.

Now, the player has some logic that applies in most states, like gravity, so I can have that logic in a main player class so it doesn't get repeated in every state. But also logic that only applies in certain states, like being able to jump or attack, changing directions etc. How do I reuse the same logic in multiple states without moving it to the player class, using a lot of if statements or duplicating it between states?

# Answer
*Keep in mind that there is not a single one way to go about this.*

If the issue is how to reuse behavior. I want to encourage to separate state and behavior in your mind.

Yes, there is an state machine. And yes the behavior of your player character changes with its state. But state and behavior are not the same thing. For example, you have some behavior that does not depend on the state. And you want to have behavior shared among some states but not others.

So, I suggest to have a list of behaviors per state. Which you execute in order. And, perhaps, you have some behaviors in multiple of these lists. *Yes, those are behavior objects.*

---

*I want to suggest an organization that has worked for me. It is not a silver bullet by any means. But it might be adequate for you.*

If you consider physics something external to the behavior. Then it follows to not allowing the behaviors to interact directly with the physics engine. They of course, need to interact somehow. For that, you can allow them to get and set properties of the main class.

I'll tell you what I settled into. The main class update method does these steps:

* Motion.

Here you do physics based motion that works regardless of the state. Basically these:

+ Rotation. There is a target direction that behaviors can set, and there are rotation speed variables the the behaviors can set as well.
    + Translation. Using the velocity we got, of course. By the way, you may find useful to allow the behaviors to set a property to have player character snap to a surface.
    + Collisions. So we moved, did we collide? Did we bounce or slide? Do we need to update position or velocity?

If I need to tell the physics engine to update something else based on what the behaviors are doing, I would add it here. For example, I suppose we could add stuff like drag and friction.
* Physics checks.

You know, raycasts and stuff. Gather any information about the physical surrounding that you want to be available for the behaviors to read. *Including - but not limited to - ground checks.*
* Update Velocity (Gravity and other accelerations).

Turns out I need to give accelerations a special treatment. While I could keep accelerating against an obstacle (e.g. gravity on the ground), I don't want to (you don't want the speed to build up, and have the player character tunnel through). And doing it after knowing the result of physics checks allows me that.

To be clear, we use accelerations to update velocity. But velocity can be set by other means. Including externally or form the behaviors (running and jumping behaviors do this).

By the way, the world controls gravity, not the behaviors. However, the behaviors can set a gravity factor.

*We can also enforce terminal velocity here.*
* Update Target Direction.

Based on the results of physics checks, and also on the velocity after accelerations has been applied, I update the target direction. *This could be done by a behavior. In fact executing behaviors is the next step, so it won't break much to do so.* However, I have decided that direction is responsibility of the main class, since rotation is responsibility of the main class.
* Execute Behaviors.

Here is where the behaviors for the current state get to run. And yes, multiple per state. With some reused between multiple states.

I actually let the run behavior execute in the air, so you have air control with the same logic, even if the state is jumping.

Consequently the run behavior cannot be responsible of setting animations. In general, I have separate behaviors for setting animations and effects based on the current state.

On a similar note, I have found useful to define parameters for air and ground… Which are not states of the state machine. Instead they are part of the results of the physics checks that the behaviors can read. And based on that the behavior picks the parameters it will use.

With this approach I have clarity of where everything goes. Also notice that most of the conditional behavior in the main class is not controlled by if statements, but by setting speeds or accelerations or factors which if set to zero would disable that behavior, but that does not require additional flow control. *Snapping to a surface is the glaring excpetion.*
> 3 votes

---
Tags: software-engineering, platformer, design-patterns, fsm
---


title: Tile system Meta data

text:
# Question
Title: Tile system Meta data
I am creating a strategy game in LibGDX with a tile system and destructible tiles. I am using an array of enums to represent the different types of tile, eg:

```
public enum TileType {AIR, DIRT, STONE, etc.};

```

and then:

```
private final TileType[] tiles = new TileType[maxTiles];

```

to get a tile 4 across and 2 down i can just use:

```
targetTile = tiles[2 * mapWidth + 4];

```

This works really well for everything; its quick due to locality of reference etc.

Except... I don't know how to integrate meta-data into the tiles -- for example, if I have a tile called "FACTORY" that is supposed to create units that can then go out to fight. Since enums can only have global data, "FACTORY" can't store stuff like a factory's health or how far it is through constructing a unit, etc.

For entities, I am currently using their on individual handlers, eg:

```
public class Soldiers {
    float[] x; float[] y; float[] health; // etc. (using arrays for DOP)
}

```

But soldiers arent tiles -- they are their own thing (they move separate from the grid and have very little impact on the tiles around them so it makes sense to have them not be a part of the tile system)

I tried to have:

```
public class Factories {
    float[] health; float[] constructionWorkDone; // etc. (using arrays for DOP)
}

```

Except now I am kinda defining the 'factory' entity in two places, once by having a tile called: "FACTORY', and secondly in Factories. Additionally, the enum TileType currently stores a block's health. I am using a chance destruction system on blocks. Instead of having every tile use a health limit, there is simply a probability that a will be destroyed by a projectile (which can be scaled based on the projectile's damage). But if a FACTORY tile is destroyed, it won't have any way of telling its "class Factories" meta data that it is destroyed.

"Just use class Factories," I hear you saying, except my A\* path finding algorithm uses the tile array to navigate and it would be cool for units to avoid certain buildings, etc. Additionally, I looked a little into Minecraft's design and (I might be wrong, but) it has both a "chest" voxel while the chest metadata is stored elsewhere. (This needs citation though)

Is there a simple way through?

# Answer
> 1 votes
Use other arrays for building type (e.g. "factory") and building id. Or use a structure that holds them along the tile type.

Then, each tile will have a tile type, a building type and a building id. You can either have a "building" tile type, and only use the other two values when that is the tile type. Or you can allow building on any tile type, for which you will need a "no building" building type.

So you can use the building type to know where to look, and the building id to index it. And that is how you can find the information about the building that is on the type.

Just in case, I'll also mention that these buildings won't store their position. It is responsibility of the tiles to give them position. Thus, your path-finding algorithm does not need to query the the structure with the information about the buildings to know where they are, instead they look at the tile to know if there is a building there.

---
Tags: java, libgdx, tiles, strategy
---


# Question
Title: How to flip enemy patrolling side to side with Mathf.PingPong?
I am making a 2D platformer in Unity and I programmed one of the enemies to move back and forth with the ping pong function.

I would like to change the local scale depending on which direction the character is moving.

I have tried using two if statements where if the x value of the transform is below or above a certain number it will change the local scale accordingly, but that did not work.

Here is the code for the enemy:

```
public class Bunny: MonoBehaviour  {

    float min;
    float max;
    [SerializeField] float movmentSpeed = 0.5f;
    float movementDistance;
    public bool isHit = false;

    void Start() {
        min = transform.position.x;
        max = transform.position.x + 3;
        movementDistance = max - min;
    }

    void Update()  {
        if(isHit == false) {
            transform.position = new Vector3(
                Mathf.PingPong(Time.time * movmentSpeed, movementDistance) + min,
                transform.position.y,
                transform.position.z
            );
        }
    }
}

```

# Answer
> 0 votes
You can do this without an extra member variable, and without overshooting past min/max. "Moving left" just means your new x is less than your old x. So, compare to see which one is bigger.

```
float newX = Mathf.PingPong(Time.time * movmentSpeed, movementDistance) + min;

transform.localScale = new Vector3(
    newX < transform.position.x ? -1 : 1,
    1,
    1
);

transform.position = new Vector3(
    newX,
    transform.position.y,
    transform.position.z
);

```

# Answer
> 0 votes
The problem with the `Mathf.PingPong` function is that it doesn't tell you if the returned value is from the "Ping" or the "Pong" phase. When you need that information, for example because you need it to decide in which direction the sprite is supposed to face, then it is not going to be of much use. So we are going to need to use a different solution here.

One simple solution is to have a variable which states if the bunny is currently moving left or right. I would prefer to use an `enum` for that purpose, but when you don't know how to use enumerations yet, then you can just use a flag `bool isMovingLeft`.

Then you implement the Update function to behave differently depending on the state of that variable:

```
if (isMovingLeft) {
    transform.Translate(-movementSpeed * Time.deltaTime, 0f, 0f);
} else {
    transform.Translate(movementSpeed * Time.deltaTime, 0f, 0f);
}

```

Then you need to detect if an event occurred which would cause the bunny to turn around, and then do everything that entails. In that case this event would be to exceed the "max" or "min" value:

```
if (transform.position.x > max) {
    isMovingLeft = true; // move left from now on
    transform.scale.x = -1f;  // flip the sprite to mirrored
}
if (transform.position.x < min) {
    isMovingLeft = false; // move right again from now on
    transform.scale.x = 1f; // flip the sprite back to normal
}

```

# Answer
> 0 votes
Try it, simple and easy way to flip in a specific range. It worked for me.

```
if (transform.position.x > max)
            transform.Rotate(0f, 180f, 0f);
else if (transform.position.x < min)
            transform.Rotate(0f, -180f, 0f);

```

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


title: Gyroscope Parallax Effect In Unity

text:
# Question
Title: Gyroscope Parallax Effect In Unity
I want to make a parallax effect in Unity 3D with gyroscope like the one on this site: http://matthew.wagerfield.com/parallax/

I found an asset, but it is too expensive.

So I need a script which I can set to the GameObject, so it would move depending phone's gyroscope.

# Answer
It's not so hard to find some sources from google;

Parallax effect (logic):
How do I implement parallax scrolling in 2D?

Gyroscope:
http://docs.unity3d.com/ScriptReference/Gyroscope.html
http://docs.unity3d.com/ScriptReference/Input-gyro.html
> 1 votes

# Answer
You are asking like "Gimme a script dammit!". Well, i can't give you a script. But i can tell you how to write your own.

Parallax effect basically means moving background objects slower than foreground ones to create a fake 3D (or depth) effect.

So if you have a vector that represents foregound velocity like:

```
//values and names are example
Vector3 foregroundVelocity = new Vector3(10,0,0);

```

Than you can use these vectors for background velocity (not limited to these):

```
//values and names are example
Vector3 backgroundVelocity = new Vector3(7,0,0);
Vector3 evenMoreBackgroundVelocity = new Vector3(5,0,0);
Vector3 farFarAwayVelocity = new Vector3(3,0,0);
Vector3 rightInFrontOfHorizonLineVelocity = new Vector3(1,0,0);

```

Then you can get gyro input from Unity's own Gyrpscope class, as @AhmetZambak mentioned, and just move your sprites (or gameObjects) according to magnitudes of corresponding angles, like:

```
//pseoudocode
Vector3 eulerGyroAngles = /*your input reading code*/;
gameObject.transform.position = (eulerGyroAngles.y, eulerGyroAngles.x, 0) * (corresponding magnitude vector);

```
> 1 votes

# Answer
Unity-Gyroscope-Parallax

There is a free plugin for gyroscope parallax effects, it can move object position and/or rotate object in space via gyroscope input data as gravity vector or as a movement in space direction.
> 0 votes

---
Tags: unity, c#, 2d, parallax-scrolling
---


# Question
Title: Animation of front and back part of a prefab separately on unity
I'm trying to animate a platform front and back.

Because, when my character will be on it, it want the front of the platform to be in front of the character.

Here is what I have so far :

The thing is, now I want to animate it, and the little green part that you can see on the left is moving and have to come in front of my character. BUT, when the green part is on the back then my character has to be in front of it.

The order is this :

```
backpart : order in layer : 9
character : order in layer : 10
frontpart : order in layer : 11

```

And, the backpart and frontart are together in a prefab like this :

```
- backpart
   - frontpart (son of backpart)

```

I have no problem to animate the backpart but I can't find any way to animate the frontpart WITH the backpart.

In the animation window I can't put a second row of sprite and I don't know the other way so I'm kinda stuck.

# Answer
> 1 votes
I actually found how to do it by myself.

On the animation window, click on "Add property" \> the name of the child object (in my case, frontpart) \> "SpriteRenderer" \> "Sprite".

And voilà, a new row appears and you can put your image on it!

---
Tags: unity, animation, animator
---


# Question
Title: Unity Engine Movement Script Causes Shark To Fly
This code is for controlling a shark

I want to have continuous collision detection which won't work with MovePosition so I tried changing it other options but those are making the Shark Fly

Why does converting this line

```
Rb.MovePosition(transform.position + SharkCamera.transform.forward * CurrentSpeed * Time.fixedDeltaTime);

```

to this

```
Rb.velocity += SharkCamera.transform.forward * CurrentSpeed * Time.fixedDeltaTime;

```

or this

```
Rb.AddForce(-transform.right * CurrentSpeed * Time.fixedDeltaTime, ForceMode.VelocityChange);

```

makes the Shark fly?

Note: Directly setting the velocity won't work because other forces are acting too

# Answer
Let's recap some dimensional analysis:

* a **Displacement** measured in \\$m\\$, which is different from...
* a **Velocity** measured in \\$\frac m s\\$, which is different from...
* a **Force** measured in \\$\frac {kg \ m} s\\$

Because these are different quantities, taking code for one and copying it into another will not yield the same effect.

Let's dimensionally analyze what you're trying to add:

```
SharkCamera.transform.forward * CurrentSpeed * Time.fixedDeltaTime

```

$$\require{cancel}\text{(dimensionless)} \cdot \frac m {\cancel s } \cdot \cancel s = m$$

So this is producing a value in metres, so it's a displacement. A displacement is not a velocity, so you can't add it to your velocity. What your code there does is keep adding more and more to your velocity every frame, so your object keeps getting faster and faster.

If you want to make the velocity point in a certain direction with a certain magnitude, just assign it with `=`, don't accumulate it with `+=`:

```
Rb.velocity = SharkCamera.transform.forward * CurrentSpeed;

```

Note that we don't need to multiply by delta time - we're not taking the speed and integrating it over a time interval to make a displacement, we're using the speed as a speed, natively. Repeating the dimensional analysis on this, we get \\$ \frac m s\\$, which is exactly the unit we expect for a velocity.

Try this exercise of checking whether your units make sense anytime you're doing anything with physics - it's a great debugger to spot when you're writing code that makes no sense.

---

To help this play more nicely with other forces, you can instead apply an acceleration *toward* your target velocity, rather than setting the velocity directly. That might look like this:

```
// Compute the velocity we want to have:
var targetVelocity = SharkCamera.transform.forward * CurrentSpeed;

// Compute its difference from our current velocity.
var deltaV = targetVelocity - Rb.velocity;

// Set a budget for how much we can change our velocity this frame.
var accelLimit = acceleration * Time.deltaTime;

// Scale our change so that it does not exceed the acceleration limit.
deltaV = Vector3.ClampMagnitude(deltaV, accelLimit);

// Apply the velocity change.
Rb.AddForce(deltaV, ForceMode.VelocityChange);

```

You can increase your `acceleration` parameter to make the controls tighter and more responsive, or decrease it to make more gradual ramp-up.

You can apply lots of other changes too - like taking some of `Rb.velocity.y` and blending it into `targetVelocity.y`, or scaling `deltaV` so that your vertical acceleration change is damped relative to horizontal, or scaling your acceleration limit by how closely the direction of velocity change aligns with the shark's forward axis, etc. Any of these techniques can help you dial in the right swimming feel.

---

You can also just get continuous collision detection with `MovePosition` and keep your existing code, contrary to your assumption that this is impossible.

Just scan for collisions *before* you move:

```
// Compute length of a full move.
var distance = CurrentSpeed * Time.deltaTime;

// Sweep a capsule from where we are to the end of the move.
if (Physics.CapsuleCast(
       transform.position - transform.forward * capsuleLength,
       transform.position + transform.forward * capsuleLength,
       capsuleRadius,
       SharkCamera.transform.forward,
       out RaycastHit hitInfo,
       distance,
       obstacleLayers)
) {
    // If the swept test hits something, stop just a hair before the collision.
    distance = hitInfo.distance - 2 * Physics.defaultContactOffset;
}

Rb.MovePosition(transform.position + SharkCamera.transform.forward * distance);

```
> 0 votes

---
Tags: unity, physics
---