# Question
Title: Is There an Easy Way to Convert Python/Pygame code into C#?
I am working on a game, sort of like this and I want to convert it to C#, as it is currently written in Python. The reason of this is because I can add features more easily and with less writing in C#, and I do NOT want to write it all again, with all of the glitches and testing having to be redone. Is there any program of internet service that can do so, for free? I don't have extra money to spend on this, which is just for fun. Thanks for all feedback, edits, and suggestions!

Edit: I use Wing IDE 4.1 for my Python coding and the Unity Version of MonoDevelop for C#.

# Answer
> 3 votes
In general, "translating" code from one language to another (or to run on one system or another) is called a **port** (note interesting relation or *port* to *portable*).

Ports take a lot of work, and although there are many tools out to "help" you perform the task of porting, it's largely going to be a manual process.

If you want to program in C#, a good thing to do is just re-implement your program in C#, using your Python code base as a reference. Along the way you could find and make some improvements.

# Answer
> 1 votes
There is a free online tool to convert Python to C#.

https://pythoncsharp.com

This is an automated conversion, so will not be perfect but will bring across the control of flow and general structure of a script.

---
Tags: c#, python
---


# Question
Title: What type does one cast the result of "get_function_address" to in order to call the function within a C++ DLL?
According to the game maker documentation for dll manipulation:

> get\_function\_address('function\_name')
>
> Returns the address of a GameMaker function. This can be passed to DLL's so the can call directly into GameMaker.
>
> This feature is unsuported, so care must be taken when using this function.
>
> **Please Note: These functions use Delphi 2010 PASCAL calling convention and string formats.**

Let's assume one writes a C++ dll and wants to use those function pointers to make game maker function calls within the dll code.

What does one cast the function pointer to? I am familiar with passing a C function pointer to a C++ dll (it is blatantly obvious what you cast the pointer to; the same thing as what you would within the C code). However, I do not know what I would cast functions to coming from game maker. I imagine it is a relatively "simple" thing to do once you know the magic dance. It just doesn't say anywhere what to do.

I think the page might be trying to tell me that this is equivalent to passing a pascal function pointer to a C++ dll. I don't really know. I can't be the only guy with this problem.

# Answer
> 0 votes
This answer can either be incredibly simple or incredibly complicated. First let’s get something out of the way. That document is for game maker 8.1 not 8.0. This in turn means you cannot use that function as it doesn’t exist for 8.0.

However this does not mean you cannot call game maker functions within the dll. Consider the example function game\_maker\_function\_a(x,y,z). It takes in three values and does stuff. For the purposes of this explanation the behavior of the function is irrelevant. It has a return value. We will get to that.

Every game maker function has at most 14 arguments. They either take in a double or a char\*. Therefore any function can can be represented via a structure. We can do this in C++ easily. Then using any method one sees fit one can make a list to hold function call representations. Then in game maker one would access this list and get the data contained in that function call.

The only minor annoyance in calling game\_maker\_function\_a in this manner is to call function pointers in game maker. This can be done with a script ID and execute\_script. This requires one to make a wrapper script for the game maker function.

Finally the function call struct can hold a pointer to the location of the variable that will hold the return value.

Pros: You can call game maker functions in a dll.

Cons: Technically you are only queueing up function calls which will have to be executed upon exiting the function.

**This design should be future compatible with studio and beyond.**

---
Tags: c++, game-maker
---


# Question
Title: Passing touch position to compute shader
I am working on a game where I have to mix colored liquids as shown here. I am working with a plugin (StableFluids) to get this effect: Effect

**Problem:**

The shaders used in the plugin are able to create the effect I want but the effect is created in the wrong position; rather than being triggered at the point where the user’s finger is touching the screen, the effect is being triggered at other points.

**Implementation:**

The plug-in has one compute shader which takes 2 parameters: **force origin** and **force direction**. The force direction is working properly as the deformation happens in the direction of the finger swipe. However, I am having trouble the touch input position into an accurate force origin value. I am passing the force origin value to the shader using Unity’s "RaycastHit.textureCoord".

Below is the compute shader code:

```
// StableFluids - A GPU implementation of Jos Stam's Stable Fluids on Unity
// https://github.com/keijiro/StableFluids

#pragma kernel Advect
#pragma kernel Force
#pragma kernel PSetup
#pragma kernel PFinish
#pragma kernel Jacobi1
#pragma kernel Jacobi2

// Common parameter
float Time;
float DeltaTime;

// External force
float2 ForceOrigin;
float2 ForceVector;
float ForceExponent;

// U (velocity field)
Texture2D<float2> U_in;
SamplerState samplerU_in;
RWTexture2D<float2> U_out;

// W (velocity field; working)
Texture2D<float2> W_in;
RWTexture2D<float2> W_out;

// Div W
RWTexture2D<float> DivW_out;

// P (pressure field)
Texture2D<float> P_in;
RWTexture2D<float> P_out;

// Color map
Texture2D<half4> C_in;
SamplerState samplerC_in;
RWTexture2D<half4> C_out;

// Jacobi method arguments
float Alpha, Beta;

Texture2D<float> X1_in;
Texture2D<float> B1_in;
RWTexture2D<float> X1_out;

Texture2D<float2> X2_in;
Texture2D<float2> B2_in;
RWTexture2D<float2> X2_out;

// Advect step
[numthreads(8, 8, 1)]
void Advect(uint2 tid : SV_DispatchThreadID)
{
    uint2 dim;
    W_out.GetDimensions(dim.x, dim.y);

    float2 uv = (tid + 0.5) / dim;
    float2 duv = U_in[tid] * float2((float)dim.y / dim.x, 1) * DeltaTime;

    W_out[tid] = U_in.SampleLevel(samplerU_in, uv - duv, 0);
}

// Add-force step
[numthreads(8, 8, 1)]
void Force(uint2 tid : SV_DispatchThreadID)
{
    uint2 dim;
    W_out.GetDimensions(dim.x, dim.y);

    float2 pos = (tid + 0.5 - dim * 0.5) / dim.y;
    float amp = exp(-ForceExponent * distance(ForceOrigin, pos));

    W_out[tid] = W_in[tid] + ForceVector * amp;
}

// Setup for Project step (divW calculation)
[numthreads(8, 8, 1)]
void PSetup(uint2 tid : SV_DispatchThreadID)
{
    uint2 dim;
    W_in.GetDimensions(dim.x, dim.y);

    DivW_out[tid] = (W_in[tid + int2(1, 0)].x - W_in[tid - int2(1, 0)].x +
                     W_in[tid + int2(0, 1)].y - W_in[tid - int2(0, 1)].y) * dim.y / 2;

    P_out[tid] = 0;
}

// Finishing for Project step (divergence free field calculation)
[numthreads(8, 8, 1)]
void PFinish(uint2 tid : SV_DispatchThreadID)
{
    uint2 dim;
    W_in.GetDimensions(dim.x, dim.y);

    if (any(tid == 0) || any(tid == dim - 1)) return;

    float P1 = P_in[max(tid - int2(1, 0), 1)];
    float P2 = P_in[min(tid + int2(1, 0), dim - 2)];
    float P3 = P_in[max(tid - int2(0, 1), 1)];
    float P4 = P_in[min(tid + int2(0, 1), dim - 2)];

    float2 u = W_in[tid] - float2(P2 - P1, P4 - P3) * dim.y / 2;

    U_out[tid] = u;

    if (tid.x == 1) U_out[int2(0, tid.y)] = -u;
    if (tid.y == 1) U_out[int2(tid.x, 0)] = -u;
    if (tid.x == dim.x - 2) U_out[int2(dim.x - 1, tid.y)] = -u;
    if (tid.y == dim.y - 2) U_out[int2(tid.x, dim.y - 1)] = -u;
}

// Jacobi method with a scalar field
[numthreads(8, 8, 1)]
void Jacobi1(uint2 tid : SV_DispatchThreadID)
{
    X1_out[tid] = (X1_in[tid - int2(1, 0)] + X1_in[tid + int2(1, 0)] +
                   X1_in[tid - int2(0, 1)] + X1_in[tid + int2(0, 1)] + Alpha * B1_in[tid]) / Beta;
}

// Jacobi method with a vector field
[numthreads(8, 8, 1)]
void Jacobi2(uint2 tid : SV_DispatchThreadID)
{
    X2_out[tid] = (X2_in[tid - int2(1, 0)] + X2_in[tid + int2(1, 0)] +
                   X2_in[tid - int2(0, 1)] + X2_in[tid + int2(0, 1)] + Alpha * B2_in[tid]) / Beta;
}

```

Questions:

1. What kind of conversion is required to convert the touch input position to the shader’s coordinate system so that the effect appears where the finger has touched?
2. Are there any other open-source plug-ins to implement the required effect that have a clearer relationship between the touch input and the shader effect coordinates?

I would appreciate any suggestions and thoughts on this topic. Thank you.

# Answer
Solution:

1. Get texture coordinate of touched position using "RaycastHit.textureCoord" method
2. That texture coordinate will be in the range from (0,0) to (1,1)
3. Convert that texture coordinates to the coordinates that shader can understand. (0,0) is the center of the screen and (0,0) is bottom left on texture. Using the basic lerp method, you can convert those coordinate systems.
> 0 votes

---
Tags: unity, shaders, compute-shader
---


# Question
Title: Basic pseudocode to create a rope physics
I am trying to simulate the physics of a 2D hanging rope, consistent of a series of n-links. It could be a series of four pendulums. I just want some movement of the rope and the ability to contact with the ground. I was inspired by this question and this one.

I would like to programme it from zero in Python or a similar modelling program, but I don't find simple maths to recreate this effects. Which are the basic equations to escalate a series of n-links to resemble like a rope, please?

# Answer
> 1 votes
The article linked below provides good starting pseudocode. With images and video. I actually used it to create fishing rope in my previous game too.

Simulate Tearable Cloth and Ragdolls With Simple Verlet Integration

* Rope is just 1D of cloth simulation.
* `ability to contact with the ground` To make it able to react with game world you need link it with game collision code. In your case Python, I dont know which will you use. But for my case Unity, I put tiny SphereCollider on each rope node and it can now rest on ground.

# Answer
> 1 votes
2D rope physics in pseudocode with explanations: http://web.archive.org/web/20160418004153/http://freespace.virgin.net/hugo.elias/models/m\_string.htm

Other models explained by Hugo Elias: http://web.archive.org/web/20160418004148/http://freespace.virgin.net/hugo.elias/models/m\_main.htm

---
Tags: rope-physics
---


# Question
Title: How to access the raw memory of d3d model in game maker?
I am using the d3d model creation functionality in Game Maker. I also use dlls and I want to be able to modify a 3D model (change uv values) without recreating a model. Is there a way to locate the address of the model’s memory and use pointers to directly change the values? Is this possible and how would I go about doing it?

# Answer
> 0 votes
There is not a built-in function for this. In GameMaker: Studio and newer, you would probably use buffer\_get\_address and pass the updated buffer to vertex\_buffer\_create\_from\_buffer, but in GM8.x (which the question author uses) that was not yet a thing.

What follows requires a degree of determination.

First you would want to find out an address of a built-in `d3d_model_*` function. I'll use `d3d_model_clear` here since it's one of the more straightforward ones.

Despite the amount of rewriting behind the scenes, the function stayed quite alike:

* First it `CALL`s (opcode E8) a function to pull out an integer out of the only argument.
* Then it `CALL`s (E8 again) the implementation.
* The implementation goes like this:

```
void internal_d3d_model_clear(int index) {
  if (index >= 0 && index < internal_d3d_model_count) {
    // internal_d3d_model_array is an internal_d3d_model*
    internal_d3d_model* a_model = internal_d3d_model_array[index];
  }
}

```

which in assembly means

```
TEST index, index
<JS or JL> ...
CMP index, internal_d3d_model_count
JGE ...
MOV a_model, internal_d3d_model_array // +index*4 here or in next instruction

```

With the function address in your hands you could either:

* Simply connect Visual Studio debugger to the game (Debug \> Attach to Process), look at disassembly, and copy the fixed location of `internal_d3d_model_array` from the MOV instruction. This will not work when changing GM versions
* Use an instruction parser (like this one) to have it dynamically extract the location of `internal_d3d_model_array`  from the inner function.

Once you have that location, you can dereference the array pointer from it (`your_d3d_model_struct* d3d_model_array = (your_d3d_model_struct*)(*(int*)that_address)`) and start investigating what is stored inside each model using the memory viewer or Watches window in Visual Studio - considering the circumstances, I would guess that there is another pointer to either raw vertex buffer data or an array of structs representing diffferent primitive operations.

---
Tags: game-maker
---


# Question
Title: Efficient way to build a 360 rotation system with clockwise and counterclockwise direction
I've been struggle with rotation for sometime now, maybe it isn't that hard for someone who dominates the mathematical side of things regarding rotation and angles but, I need to build a rotation system that rotates the player to either clockwise or counterclockwise direction according to the nearest direction to the target angle.

I.E.

If my player is rotated to 45° and the direction is changed to 135°, he must rotate 90º clockwise (from 45° to 135°). If my player is rotated to the same 45° and the direction is changed to 315°, he must rotate 90° counterclockwise (from 45° to 315º).

This didn't seemed a big deal when I started, but it's been hard for me to build something that cover all the rotation possibilities, which tells me that I'm doing something wrong here. I mean, there's must be a couple of formulas that fit this problem and cover all the possible rotations or something.

Right now, my rotation system is configured to a minimal of 5 degrees of rotation, wich means that the possible degrees goes from 0 to 355(it never get to 360, going back to 0 instead).

I don't have a code to show cause everytime I try to build this, I reach to a point where there are so many possibilities that aren't covered by my tests that I end up deleting everything to try again, but I'm tired of this seemingly endless loop (for me anyway lol).

Does anyone knows a way to build this?

-EDIT-

My project is 3D and the camera perspective is similar to sports games like NBA 2K or soccer games in general. The input is a Vector2 obtained with the new input system. I need to move my player around with root motion, which means that my goal with this system is to calculate the rotation data to be passed as an animation parameter (using a event), so the correct animation is played and the player finally rotate according to the animation. The main part of the code (calculation part) was built by a friend of mine, who has more knowledge than me. This is my current code:

```
if (movementVector != Vector2.zero)
    {
        targetRotationAngle = Mathf.Atan2(movementVector.x, movementVector.y) * Mathf.Rad2Deg + cameraTransform.eulerAngles.y; //FUNCTIONAL CODE BUILT BY A FRIEND
        targetRotationAngle = Mathf.CeilToInt(targetRotationAngle / 5) * 5; //FUNCTIONAL CODE BUILT BY A FRIEND
        if (targetRotationAngle < 0)
            targetRotationAngle += 360;
        if (currentRotationAngle == targetRotationAngle)
            return;
        else
        {
            if (currentRotationAngle < targetRotationAngle)
            {
                Debug.Log("Clockwise rotation in " + (targetRotationAngle - currentRotationAngle) + " degrees");
            }
            if (currentRotationAngle > targetRotationAngle)
            {
                Debug.Log("Counterclockwise rotation in " + ((360-currentRotationAngle)+targetRotationAngle) + " degrees");
            }
        }
            currentRotationAngle = targetRotationAngle;
    }

```

This is a summarized version of my previous attempts (the ELSE part), I know my formula is wrong, cause it doesn't cover all the rotation scenarios, the more I tried to build, more of this IF's were nesting. That's why I've decided to ask...

# Answer
Unity has many built-in functions to assist you with this sort of thing. Whenever you run into a problem like this, it's a good idea to stop and think "is this an issue that's likely to affect most developers? Is it reasonable to assume there are built-in functions to make this easier?"

Some good ones, all which automatically wrap around 360 degrees:
> 1 votes

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


# Question
Title: Should I use Async & Await, instead of Coroutines, in Unity?
Should I use Async & Await in Unity? Or should I keep using Coroutines? If I should use Async & Await, how can I do so in a manner comparable to Coroutines?

# Answer
> 9 votes
In contrast to Evorlor's answer, here are some good reasons to use Coroutines:

* They've been the standard solution in Unity for many years and anyone else you bring onto the team should already be comfortable with them.
* They are in step with the engine. `WaitForFixedUpdate()` ensures that the next step in the Coroutine will be run during the Fixed Update cycle. `WaitForEndOfFrame()` ensures that the next step will be run in the Update cycle. If you use C#'s async/await, ~~there's no way to ensure~~ it's complicated to ensure that the code remains in-step with the engine (see below).
* Likewise, `WaitForSeconds()` takes the current `Time.timeScale` into consideration, something that's not possible with `await`.
* Coroutines are automatically stopped when the object that is running them is destroyed or disabled (this is occasionally undesirable, in which case you might want async/await).

**When should I *not* use coroutines?**

* When you want a coroutine-like function to return a value (see this blog post recommended by DMGregory for how to configure these to work with the main thread when needed)
* If you are having trouble getting error handling to work with your coroutine (see blog post from previous bullet. Note that you *can* put a try-catch block in a coroutine, as long as that block doesn't include a "yield" instruction).
* If you've profiled your application and found that coroutines are costing you performance overhead that you can't spare, and this can't be fixed by optimizing your coroutines (unlikely for most games)
* If you need to run a coroutine-like function from a regular C# class that doesn't extend `MonoBehaviour`
* If you need a coroutine-like function to keep runnning when its GameObject is destroyed or disabled.
* When working with a library that makes heavy use of `async` (e.g. Google Firebase)
* When your code needs to be parallel (multi-threaded). Although they can be used to improve performance by distributing an expensive operation over multiple frames, Coroutines are not threaded. When you need multi-threaded code for maximum performance, use C# Threads or the Unity Job System.
* If you have any other *good reason* not to use coroutines

In my experience, all of these exceptions are very rare and you don't normally need to consider them. YMMV depending on the project and your coding style.

# Answer
> 1 votes
**Should I use Async & Await or Coroutines?**

You should use Async & Await. Coroutines were Unity's solution to running multiple simultaneous processes at a time when the version of C# it supported did not have Async & Await. Now that Unity's version of C# supports Async & Await, Coroutines are obsolete.

**What is the difference between them?**

Coroutines check back every frame to see if the condition has been met. Async & Await set a timer, and come back when the time is up. Async & Await is more efficient, but negligibly so. Async & Await can have return values much more easily than Coroutines.

**How can I use Async & Await in place of Coroutines?**

These two code snippets behave the same way:

```
public IEnumerator CoroutineMethod()
{
    //Exits method early
    if(ShouldEarlyExit())
    {
        Debug.Log("Early exiting.");
        yield break;
    }

    //Wait until condition has been met
    yield return new WaitUntil(() => ConditionMet());
    Debug.Log("Condition has been met.");
    //or
    while (!ConditionMet())
    {
        yield return new WaitForEndOfFrame();
        Debug.Log("Condition has been met.");
    }

    //Run code every n seconds
    while (true)
    {
        yield return new WaitForSeconds(1.0f);
        Debug.Log("waiting for 1 second.");
    }
}

```

---

```
public async void AsyncAwaitMethod()
{
    //Exits method early
    if (ShouldEarlyExit())
    {
        Debug.Log("Early exiting.");
        return;
    }

    //Wait until condition has been met
    while(!ConditionMet())
    {
        await Task.Delay(Mathf.CeilToInt(Time.maxDeltaTime * 1000));
        Debug.Log("Condition has been met.");
    }

    //Run code every n seconds
    while (true)
    {
        await Task.Delay(1000);
        Debug.Log("waiting for 1 second.");
    }
}

```

---
Tags: unity, c#, multithreading, coroutines, async
---


# Question
Title: Are spritesheets worth it? Is a zip a good alternative?
I was wondering if spritesheets are worth it. I am making a game with pixi.js and was thinking about optimization, beginning with asset loading. I currently have an arraya of all files and use PIXI.loader, but I know this is not good because it will make a web request for all files which takes long, so I should figure out a way to load them in one web request. The first thing I thought of was a spritesheet but then I thought "what if I just zipped everything and loaded it with something like JSZip?" I knew it was possible already (from this project that loads pixi textures from a zip) and listed what I think are potentials good and bad things:

Zip good points:

* Compression meaning faster loading of assets
* Compression meaning smaller build size when making a build with electron

Zip bad points:

* Requires loading a separate library meaning increased loading time and using more RAM
* Requires decompressing in-memory meaning increased loading time

Spritesheet good points:

* Doesn't has the headers of all individual image files
* Is much used so it is a proven technique

Spritesheet bad points:

* No compression (or at least not comparable to zipping)
* More than one network call due to phone limitations preventing sometimes files over 2024x2024px making it necessary to split spritesheets
* Empty holes as all images are not the same size and there is almost always a bit of space left in the spritesheet, meaning useless pixels that are still transfered over the network

I am not a very experienced developper, so I have a few questions:

1. Did I miss a point above?
2. Are spritesheets generally worth it?
3. Which technique of both is more worth it? I could do both but I want to focus on one first and leave the other in a nice to have list.

# Answer
> 4 votes
First of all, there are already image formats with compression. In particular the PNG format supports lossless compression. Furthermore, while it is true that taking a bunch of PNGs and zipping them might be a gain in size, making a texture atlas (spritesheet or similar) will also reduce the size in similar fashion, in particular if you rank up the PNG compression level when exporting the image.

Thus, a properly exported texture atlas will give you the benefits you list on compression.

Does this mean that you should make everything into a single spritesheet? No. You should put together things that should be loaded together.

It might also be worth noting that spritesheets work better when your images are small and of regular sizes. It might be you are working in a scenario for which spritesheets are not well suited.

Is that the case? I don't know. Do experiment. If you are not willing to try both techniques to decide, the engineering approach suggest to go with the proven method, and that would be a texture atlas.

You might also be interested in packing algorithms that may minimize the holes in the texture atlas.

---
Tags: javascript, optimization, spritesheet, pixi.js
---


# Question
Title: What's the Unity way of implementing data driven UI
I'm used to application development with frameworks like Qt, and I'm really fond of using MVC-like patterns. Now I'm diving into game dev and I have a bunch of data that I want to show the user and I'm wondering the Unity way to do that. For example, say I want a flyout menu that appears on hover of an ability that looks like this badly drawn paint image below:

Say I have 60+ abilities on paper that all have the following data:

* ability art icon
* name
* description
* attributes such as cooldown amount, type, modifiers, etc

I want to make it such that I can feed some system this data and it just displays the correct thing at the right time. This way when I add new abilities the system already just knows how to handle it.

**My question:**

**What is the Unity way to:**

1. **Store this data?**
2. **Use this data to drive a UI element?**

I've looked at scriptable objects, they seem like they will play a role here but I'm still unclear as to how that gets mapped to UI elements. I'm also guessing that scriptable objects are preferred over reading in a JSON file or data on a database? Maybe someone can confirm that. I suppose I'm asking for best practice here.

# Answer
> 2 votes
I generally prefer ScriptableObjects for storing data that:

1. You want to be editable with a GUI in the Unity Editor (as they can be edited in the Inspector much like the components on a GameObject)
2. Is determined at design time and will not change at runtime
3. You want to be able to assign to fields in the Unity Inspector

Here's the typical strategy I'll use for this:

```
//Data model
public class Ability : ScriptableObject {
    [SerializeField] private string displayName;
    [SerializeField] private string description;
    //etc

    public string DisplayName => displayName;
    public string Description => description;
    //etc
}

//Component for UI view
public class AbilityPresenter : MonoBehaviour {
    [SerializeField] private Text nameText;
    [SerializeField] private Text descriptionText;
    //etc

    private Ability model;

    public Ability Model {
        get => model;
        set {
            model = value;
            Refresh();
        }
    }

    private void Refresh() {
        if (model != null) {
            nameText.text = model.DisplayName;
            descriptionText.text = model.Description;
            //etc
        }
    }
}

```

This is probably most analogous to the Model-View-Presenter pattern (MVP), where the `AbilityPresenter` component would be the presenter, and a corresponding UI prefab would be the view.

If you'd also like to display your data in list form and are looking for a way to save some time, I sell a package on the Unity Asset Store that uses the above strategy for displaying sets of data in a list. In this package, you define a data model (which can be any struct or class) and view component very similar to the above, and a corresponding UI prefab. Then you can simply pass sets of data into the list controller and it will automatically instantiate view instances from the prefab and feed them the data models

**EDIT:** If you need to display a combination of static and dynamic data, one way is to wrap the static data in a container:

```
public interface IWeapon {
    string DisplayName { get; }
    float Damage { get; }
}

public class Weapon : ScriptableObject, IWeapon {
    [SerializeField] private string displayName;
    [SerializeField] private float damage = 10;
    //etc

    public string DisplayName => displayName;
    public float Damage => damage;
    //etc
}

public class DamageScaledWeapon : IWeapon {
    private Weapon weapon;
    private float damageMultiplier = 1;

    public string DisplayName => weapon.DisplayName;
    public float Damage => weapon.Damage * damageMultiplier;
    public float DamageMultiplier { get => damageMultiplier; set => damageMultiplier = value; }
    //etc

    public DamageScaledWeapon(Weapon weapon) {
        this.weapon = weapon;
    }
}

//Can display a Weapon or a DamageScaledWeapon
public class WeaponPresenter : MonoBehaviour {
    [SerializeField] private Text nameText;
    [SerializeField] private Text damageText;
    //etc

    private IWeapon model;

    public IWeapon Model {
        get => model;
        set {
            model = value;
            Refresh();
        }
    }

    private void Refresh() {
        if (model != null) {
            nameText.text = model.DisplayName;
            damageText.text = model.Damage.ToString("N1");
            //etc
        }
    }
}

```

---
Tags: unity, 2d, architecture, mvc
---


# Question
Title: How can I stop and resume a coroutine over and over again?
I want a coroutine to enter by default and then to stop when any input is given to it but then after some code to return again as active. So basically to start and stop a coroutine as many times as it's needed.

# Answer
My approach to this problem would be to create a coroutine which actually runs all the time but changes its behavior based on a bool variable.

```
public class ToggleableCoroutine : MonoBehaviour
{
    private bool coroutineActive;

    void Start()
    {
        StartCoroutine(MyCoroutine());
    }

    void Update()
    {
        if (Input.anyKeyDown) {
            coroutineActive = !coroutineActive;
        }
    }

    private IEnumerator MyCoroutine() {
        while (true) {
            if (coroutineActive) {
                Debug.Log("Coroutine is active");
            }
            yield return new WaitForSeconds(1.0f);
        }
    }
}

```
> 0 votes

# Answer
Adapted from Philipp's answer. This will start and stop the coroutine as needed.

```
using System.Collections;
using UnityEngine;

public class ToggleableCoroutine : MonoBehaviour
{
    private Coroutine myCoroutine;

    void Update()
    {
        if (Input.anyKeyDown)
        {
            if (myCoroutine != null)
            {
                StopCoroutine(myCoroutine);
            }
            else
            {
                myCoroutine = StartCoroutine(MyCoroutine());
            }
        }
    }

    private IEnumerator MyCoroutine()
    {
        while (true)
        {
            Debug.Log("Coroutine is active");
            yield return new WaitForSeconds(1.0f);
        }
    }
}

```

Although I recommend using Async & Await, instead of Coroutines: Should I use Async & Await, instead of Coroutines, in Unity?
> 0 votes

# Answer
If I have not misunderstood, your question just boils down to how you can start and stop a coroutine. Here's how you can do that -

Let this be your coroutine:

```
IEnumerator DoSomething()
{
    //Do that something
    yield break;
}

```

To start the coroutine:

```
StartCoroutine("DoSomething");

```

To stop the coroutine:

```
StopCoroutine("DoSomething");

```

Now, for your particular requirement, you can do this:

```
private void Start()
{
    StartCoroutine("DoSomething");
}

private void Update()
{
    //Stop the coroutine if 'S' key is pressed
    if (Input.GetKey(KeyCode.S))
        StopCoroutine("DoSomething");

    //Start the coroutine if 'W' key is pressed
    if (Input.GetKey(KeyCode.W))
        StartCoroutine("DoSomething");
}

```
> 0 votes

---
Tags: unity, coroutines
---


# Question
Title: How do I bring a child object in its original position after it is translated and rotated?
1. This is the original position of the cube and its child object cone.
2. Over here, I have translated the cone for 2 units
3. Now I have rotated the parent cube around 25 degrees wrt to the Y-axis
4. If we translate the cone 2 units back again, it's not in the original position

What formula do I need to apply to the cone while translating it back to bring it back to it's original position?

Code: The below code is a coroutine for translating the child object

```
  IEnumerator MoveToNewPos()
 {
       Vector3 newPos += Quaternion.Euler(0, 0, 135) * Vector3.left * distance;

    float t = 0;
    float animTime = 30;
    isMoving = true;
    for (; Vector3.Distance(transform.position, newPos) > 0.001f; t += Time.deltaTime)
    {
        float p = t / animTime;
        transform.position = Vector3.Lerp(transform.position, newPos, p);
        yield return null;
    }
   isMoving = false;
}

```

# Answer
This is probably easiest if you work in terms of `localPosition` instead of `position`.

`localPosition` tracks your offset relative to the parent coordinate space, so it's unaffected by the parent's rotation.

I also modified your routine below to make the rate of movement linear, since that's what your `p` calculation seemed to assume, but your `Lerp` was inconsistent with this.

```
IEnumerator MoveToNewPos(Vector3 destination)
{
    Vector3 origin = transform.localPosition;

    float animTime = 30;
    isMoving = true;
    for (float t = 0; t < 1f; t += Time.deltaTime/animTime)
    {
        transform.localPosition = Vector3.Lerp(origin, destination, t);
        yield return null;
    }

    transform.localPosition = newPos;
    isMoving = false;
}

```

Then you can move out with...

```
// Cache in a member variable, so you can return to this exact position later.
startPosition = transform.localPosition;
Vector3 newPosition = startPosition
                    + Quaternion.Euler(0, 0, 135) * Vector3.left * distance;

StartCoroutine(MoveTo(newPosition));

```

And move back with...

```
StartCoroutine(MoveTo(startPosition));

```
> 1 votes

# Answer
The answer to your question "How do I bring a child object in its original position after it is translated and rotated?" is that you apply the opposite transforms in the reverse order that you applied them.

If you've applied the following transforms to an object:

1. rotate *n* degrees, and
2. translate by vector *v*,

you return it to it's original position and rotation by:

1. translate by vector *-v*
2. rotate by *-n* degrees

The reason your object isn't returning to it's original position and rotation is because there is a problem/bug in your code or object hierarchy that you haven't shared with us.

If you'd like further help solving your problem, please review How to create a Minimal, Reproducible Example and follow the guidelines for using this site.
> 1 votes

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


title: Improving FPS by disabling unity events

text:
# Question
Title: Improving FPS by disabling unity events
I am trying to improve the fps and in my scene there are 4322 scripts attached to 4322 objects. When I activate those objects the fps go down. Right now it's around 100fps when i active those objects it drops to 40fps. I found and identified these two scripts are dropping the fps signficantly. Around 20 FPS i can save by commenting the methods which i am running in lateUpdate event.

```
public class ZoomNamePlace : MonoBehaviour
{
    public CameraController camContrller;
    public float size;
    public float distance;
    void Reset()
    {
        camContrller = FindObjectOfType<CameraController>();
    }

    private void Start()
    {
        //GetComponent<TextMeshPro>().text = this.transform.parent.name.Split('_')[0] + "_" + GetComponent<TextMeshPro>().text;
    }

    void LateUpdate()
    {
       Zoom();
    }

    void Zoom()
    {
        // if(camContrller ==null)
        //  camContrller = FindObjectOfType<cc>();

        //size = (camContrller.currentActiveCam.transform.position - transform.position).magnitude;
        size = Vector3.Distance(camContrller.currentActiveCam.transform.position , transform.position);
        if (size >= 200) return;
        if ((size / 600) >= .8f)
        {
            transform.localScale = new Vector3(size / 600, size / 600, size / 600);
        }
        else
        {
            transform.localScale = new Vector3(.8f, .8f, .8f);
        }

    }

}

```

If I comment out zoom method then fps improve around 5-8.

The second script is:

```
public class lookAtIcon : MonoBehaviour
{

    public CameraController camContrller;

    void Reset()
    {
        camContrller = FindObjectOfType<cc>();
    }

    void LateUpdate()
    {
        transform.LookAt(transform.position + camContrller.currentActiveCam.transform.rotation * Vector3.forward *-1 ,
           camContrller.currentActiveCam.transform.rotation * Vector3.up);
    }

}

```

The above script `LateUpdate()` code taking around 10-15 fps.

If I comment out both script updates functionality then FPS is around 59-61. If I comment out `lookAtIcon` script Updates event then fps around 65-67 (5 FPS improvement). If I comment out `LateUpdate` script `LateUpdates` event then fps around 74-75 (10 FPS improvement).

So it's about 25 fps improvement if I disable both script Events.

Please help me how should I improve it? I am thinking to disable the event if the object is far from the camera. Is there anyway avaible to disable the event on some objects? or do you have any other suggestion to improve it?

# Answer
The best way to skip calling a MonoBehaviour message is to not declare it.

As long as your script has a method called `LateUpdate` and your script is enabled, the engine will spend some measurable time calling it.

So, we'll take the `LateUpdate` method off of our individual instances, and instead just task them with tracking a shortlist of the instances we care about updating, using the methods Philipp showed:

```
public class Billboard : MonoBehaviour {

    public static List<Transform> billboards = new List<Transform>();

    void OnBecameVisible() {
        billboards.Add(transform);
    }

    void OnBecameInvisible() {
        billboards.Remove(transform);
    }
}

```

Then a script on our camera can receive a single `LateUpdate` call, and update everything in the shortlist all at once, without the overhead of calling all 4000 individually:

```
public class BillboardDirector {

    void LateUpdate() {
        Quaternion rotation = transform.rotation;

        foreach(var billboard in Billboard.billboards)
            billboard.rotation = rotation;
    }
}

```
> 2 votes

# Answer
When you want to run some code only for objects which are on screen, then the events OnBecameVisible and OnBecameInvisible can be useful to you.

```
private bool isVisible = false;

void OnBecameVisible() {
     isVisible = true;
}

void OnBecameInVisible() {
     isVisible = false;
}

void LateUpdate() {
    if (isVisible) {
        // do something completely cosmetic
    }
}

```

But keep in mind that the visibility calculation of Unity tends to err on the side of caution. When it isn't completely sure that an object is invisible, it will consider it visible. To get the number of definitely invisible objects as high as possible, make sure you enable occlusion culling.
> 0 votes

---
Tags: unity, c#, events, first-person-shooter, unity-webgl
---


# Question
Title: How to handle enemies outside camera view in 2d platform
i am making a 2d platformer in unity like mario or adventure island, and i am placing enemies manually(not doing any spawning) in the world, and those enemies have animations and movement scripts with update function.

And now my question is, how can i handle the enemies outside camera view.
I just want that the enemies should update/animate/move only when they come inside the camera view, otherwise they should be fixed where they were manually placed in the world.

Maybe not only enemies but other things like coins, stars, etc(having different animations and scripts)

Should i need to use some collision trigger, like attaching trigger to camera and detecting each enemies entered inside it and enabling animations and scripts on them.
Please tell me if that is an efficient way or if not please tell me if there is any simple and efficient way to do this.
Please correct me if there's anything wrong. Thank you.

# Answer
> 1 votes
I handled that by using pooling (i.e. just enable/disable) for the interactive enities that are far/close to the camera view. The tricky part is do you want the logic to resume or restart upon reenabling them. In entity code you should be careful what values you set to be cached (or reset) when you disable entities (you can use OnEnable/OnDisable methods to do that). Another thing to remember is that coroutines are stopped on disabling, while (Fixed)Update behaves more akin to a pause. But you can still get around that by caching or re-initializing values.

I use 2 rectangular trigger-colliders attached on the camera. The smaller rectangle is used as a region to spawn the entities before they appear on the screen. And the far bigger one to despawn them. The despawn region is bigger to avoid common situation where an entity is despawned just after spawning it due to its initial movement being in direction away from the screen. This approach of 2 colliders with different sizes requires your spawner to check if the entity that is to be spawned is not already spawned (and just went outside of the smaller spawn region but is still inside the bigger despawn region). I.e. each spawner should always know if the entity/entities it controls is/are currently enabled or disabled to avoid double spawning.

---
Tags: unity, platformer
---


title: Efficiently color a procedural mesh?

text:
# Question
Title: Efficiently color a procedural mesh?
I'm creating a procedural world with LWJGL and GLSL. I want to better visualize the biome map being produced and the height map it creates, but my attempts so far have been very inefficient. My first idea was to make a vec3\[\] holding the biome color for each vertex, but that very quickly took the game from 150 fps to 10-15. The time to render a 512x512 chunk went from around 3 per second to one per five seconds. As you could expect, there was also a problem with it very quickly using up 12gb of ram.

I then thought about making an int\[\] array for each vertex where each point of the mesh would be able to use as a dictionary to grab a vec3 for the color. So 512\*512 integers in an array getting from an array of 15 colors intead of a single array of 512\*512 vec3s. This seemed even worse somehow in both FPS and chunk rendering time.

To summarize again, I'm trying to color each vertex with its own color to visually show the biomes. What is a more efficient way to do this?

# Answer
> 1 votes
The answer is obvious in retrospect, but the solution was to create a texture and use that instead of an array. I created an image based on the biome map for that chunk when it was generated. I loaded the texture into OpenGL, and the framerate is smooth once again without half of the work.

---
Tags: opengl, java, glsl, lwjgl
---


# Question
Title: How do I manually accelerate the rotation of a sphere in Unity 3D?
I'm a little new to this so any help will be appreciated.

---

**Context:** I'm creating a VR billiard/pool game and trying to get the physics as realistic as possible. I have a cue ball being hit with a cue across a surface with accurate friction values calculated from real world trials.

---

**Problem:** The angular acceleration of the balls isn't realistic at all. Therefore the angular velocity is off (this is due to how Unity calculates physics of interaction as a point of contact rather than an area of contact and therefore friction calculation is done at one point causing it to rotate slower).

---

**Question:** How can I manually set the angular acceleration to a value in code until the angular acceleration is greater than or equals to horizontal velocity, then the angular acceleration is set to 0? Thanks in advance.

# Answer
> 2 votes
Unity doesn't have an 'angular acceleration' field that you can set. You can set the angular velocity in code, as I showed in your previous question about this. If you need to accelerate or decelerate the angular velocity, you can do this manually in your code.

```
void Update() {
    if (rigidbody.angularVelocity.magnitude < desiredAngularVelocity) {
        //scales the acceleration each frame
        rigidbody.angularVelocity = rigidbody.angularVelocity * accelerationRate * Time.deltaTime;
    }
}

```

or if you want the angular velocity to change by a constant rate rather than scaling it, I think this will work (haven't tested it):

```
void Update() {
    if (rigidbody.angularVelocity.magnitude < desiredAngularVelocity) {
        float angularSpeed = rigidBody.angularVelocity.magnitude;
        angularSpeed += acceleration * Time.deltaTime;
        rigidbody.angularVelocity = rigidbody.angularVelocity.normalized * angularSpeed;
    }
}

```

Or if you want to use forces, try `rigidbody.`AddTorque()

```
rigidbody.AddTorque(transform.right * 10000);

```

This is more complicated because torque is 3D; you'll have to calculate the correct direction for the torque.

You may wish to review all of the functions available to Rigidbodies.

---
Tags: unity, physics
---


# Question
Title: Issue with specular light at highly oblique angles with Blinn-Phong
I'm having an issue with my basic Blinn-Phong renderer, when looking at objects at very oblique angles:

I don't think this is an issue with my code, although I'll post my fragment's GLSL below. Rather, this seems to be a necessary consequence of cutting the specular component of the lighting to zero when dot(Normal, Light) \<= 0. (Which everyone tells you to do.) But doing that means there will be this discontinuity at the terminator. Removing the clamping leads to other issues; there's no more visible seam, but now the specular highlight continues around to the dark side of the sphere.

Is there a simple way around this, or is this just an unavoidable downside of the Blinn-Phong model?

# EDIT

TL;DR: It seems like this isn't just a downside of the Blinn-Phong model.

I did some more research into BRDFs and found this paper: A New Ward BRDF Model with Bounded Albedo and Fitting Reflectance Data for RADIANCE, which discusses the shortcoming of the Ward model, specifically around high grazing angles (exactly my issue!), and how they tweaked the model to fix it. Ward is an anisotropic model, but it can be simplified to be isotropic, and when you do that to their implementation-ready form from page 22, you get:

I plugged this into my code (updated below), aaaannnnnd... no dice. It looks pretty in the normal cases, but exhibits the same failure modes at the edge, and some even more spectacular ones beyond the edge (even worse than Blinn-Phong):

Note: both models are using the "shiny" param, but they mean different things to each model. The original screenshots were with shiny=.8, for Ward I had to turn it down to .1.

```
#version 150

#extension GL_ARB_conservative_depth : enable

in Frag {
    vec3 color;
    vec3 coord;
    vec3 center;
    float R;
};

out vec4 color_out;
layout (depth_greater) out float gl_FragDepth;

uniform mat4 VIEW;
uniform mat4 PROJ;

const vec3 gamma = vec3(1.0 / 2.2);
const float ambientPower = .15;
const float diffusePower = .75;

const bool PHONG = false;
const float specHardness = 60.0;
const float shiny = .1;

const bool WARD = true;

void main() {
    // Find intersection of ray (given by coord) with sphere
    vec3 eyeNormal = normalize(coord);
    float b = dot(center, eyeNormal);
    float c = b * b - (dot(center, center) - R * R);
    if (c < 0.0) {
        discard;  // Doesn't intersect sphere
    }
    vec3 point = (b - sqrt(c)) * eyeNormal;
    // Redo depth part of the projection matrix
    gl_FragDepth = (PROJ[2].z * point.z + PROJ[3].z) / -point.z;

    // Lighting begins here

    // The light dir is in world-space, unlike the others, so we have to project it to view space.
    // The direction (0, 1, 0) corresponds to the 2nd column. By the properties of the view matrix
    // (the 3x3 part is an orthogonal matrix), this is already normalized.
    vec3 lightNormal = VIEW[1].xyz;
    vec3 normal = normalize(point - center);
    float diffuse = dot(lightNormal, normal);

    float specular = 0.0;
    if (PHONG) {
        // Have to reverse sign for eyeNormal so it points out
        vec3 halfway = normalize(lightNormal - eyeNormal);
        specular = diffuse <= 0.0 ? 0.0 : pow(max(0.0, dot(halfway, normal)), specHardness);
    } else if (WARD) {
        const float PI = 3.14159265359;
        const float alpha = .15;
        const float invAlpha2 = 1 / (alpha * alpha);
        // Would move this computation to CPU and pass invAlpha2 as uniform if alpha were a parameter
        const float cFactor = invAlpha2 / PI;

        // Have to reverse sign for eyeNormal so it points out, note this is *unnormalized*
        vec3 halfway = lightNormal - eyeNormal;
        float dotP = dot(halfway, normal);
        float invDot2 = 1 / (dotP * dotP);
        float semiNormalizedInvDot = dot(halfway, halfway) * invDot2;
        // Note: You can't factor the exp(invAlpha2) part out as a constant term,
        // you'll blow out the floating-point range if you try.
        specular = cFactor * exp(invAlpha2-invAlpha2*semiNormalizedInvDot) * semiNormalizedInvDot * invDot2;
    }
    diffuse = max(0.0, diffuse);
    vec3 colorPre = (ambientPower + diffusePower * diffuse) * color
        + specular * shiny * vec3(1);

    color_out = vec4(pow(colorPre, gamma), 0);
}

```

# Answer
TL;DR: Multiply your specular value by dot(normal, lightNormal). (And *do* clamp that dot product to a minimum of 0!)

I, and I suspect (from seeing all the tutorials out there) many others, have been doing this all wrong.

I was using the Bidirectional Reflectance Distribution Function (AKA BRDF) directly to calculate specular intensity. However, the BRDF actually defines a differential quantity that is meant to be plugged into a radiometric integral. Crucially, what is usually called **the** BRDF lacks a cos(θ) term that is part of the overall integral. If you have a stomach for the math, it is discussed in more detail here: http://www.pbr-book.org/3ed-2018/Color\_and\_Radiometry/Surface\_Reflection.html#TheBRDF

When we're just dealing with point light sources, we don't need to evaluate the whole integral; the limit of the integral as a light source becomes a point goes to the integrand. But the cos(θ) term is still important.

In practice this means the shader needs a slight tweak. Results:

Above is Blinn-Phong, fixed. This is with the **same** shininess as before; because Blinn-Phong doesn't have a Fresnel term, the cos(θ) fix causes the intensity to fall off dramatically at grazing angles. But the discontinuity is gone, at least.

This is fixed Ward, with the same shininess as the 2nd image before. Fresnel reflection (roughly, higher reflection at more oblique angles) is modeled in Ward, so this looks good. And no discontinuity!
> 4 votes

---
Tags: opengl, lighting
---


# Question
Title: Microfacet model - BRDF obtain extreme values at grazing angles
I've been trying to replicate the result of this paper (linked directly to PDF paper, but you don't need to read it to give an answer) and encountered a problem with the BRDF according to the following well-known formula:

where ***F***,***G***,***D*** are Fresnel reflection, Shadow masking, and microfacet distribution respectively. The trouble I encounter is in the denominator, where ***i*** is the incident ray, ***n*** is the surface normal, and ***o*** is the angle of view.

Just by looking at the formula, probably you can already guess what happen when the ray comes from grazing angle: |i*n| approach zero, and if I look at it also at grazing angle then |o*n| would also approach zero. And as much as I hoped that F*G*D would approach zero faster than the denominator, it doesn't. (I used GGX distribution, but the same thing happen to Beckmann or Phong) The resulting BRDF I calculated is something completely different from not only the paper that I'm trying to replicate, but also from most other BRDF.

(strong peak at grazing angle, I did it for refraction case but it's the same for reflection)

(result from the paper, most brdf have this shape)

I double checked D,F and G so it can't be any of those, but then what went wrong? Has anyone tried this BRDF model and encountered a similar problem?

# Answer
Very late reply, but I had a similar issue at Issue with specular light at highly oblique angles with Blinn-Phong and the answer turned out to be Nathan Reed's last suggestion: Needing to incorporate the N.L factor from the radiometric integral.

From my experience debugging this, and eyeballing your graphs vs. the graphs you're trying to match, I'm pretty sure that's the missing bit. You can't use the BRDF directly on its own for rendering, but lots of people don't mention this.
> 2 votes

# Answer
The thing is you encounter a 0/0 problem. When the denominator goes to 0, the G goes to 0 too. 0/0 condition is what we have to avoid in program, so check G formula of GGX and you'll find the denominator (i.n)(o.n) can be factor out.
> 1 votes

---
Tags: rendering, reflection-rendering, pbr
---


# Question
Title: Why the raycast is not drawn using Debug.DrawRay?
```
private void FixedUpdate()
    {
        int layerMask = 1 << 8;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(hand.transform.position, hand.transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(hand.transform.position, hand.transform.TransformDirection(Vector3.forward) * hit.distance, Color.red);
        }
    }

```

I don't see the ray drawn anywhere when running the game in the scene view window.

I found the problem when shooting the raycast from the hand the hand rotation seems to be wrong or maybe it's in the script. When I'm running the game the yellow raycast is pointing directly up and when the hand pointing a target the yellow direction is back and up directions that's why it's never red :

The hand part I'm trying to shoot raycast from is child of a child of the player.

I added an empty GameObject position and rotation set to 0,0,0 and now it's shooting the raycast to the opposite direction not sure why :

The full script :

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

[RequireComponent(typeof(Animator))]

public class IKControl : MonoBehaviour
{
    public InteractableItem[] lookObj = null;
    public Text text;
    public float weightDamping = 1.5f;
    public float maxDistance = 10f;
    public bool RightHandToTarget = false;
    public GameObject hand;

    private Animator animator;
    private InteractableItem lastPrimaryTarget;
    private float lerpEndDistance = 0.1f;
    private float finalLookWeight = 0;
    private bool transitionToNextTarget = false;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Callback for calculating IK
    void OnAnimatorIK()
    {
        if (lookObj != null)
        {
            InteractableItem primaryTarget = null;
            float closestLookWeight = 0;

            // Here we find the target which is closest (by angle) to the players view line
            foreach (InteractableItem target in lookObj)
            {
                Vector3 lookAt = target.transform.position - transform.position;
                lookAt.y = 0f;

                // Filter out all objects that are too far away
                //if (lookAt.magnitude > maxDistance) continue;
                if (lookAt.magnitude > target.distance) continue;

                float dotProduct = Vector3.Dot(new Vector3(transform.forward.x, 0f, transform.forward.z).normalized, lookAt.normalized);
                float lookWeight = Mathf.Clamp(dotProduct, 0f, 1f);
                if (lookWeight > 0.1f && lookWeight > closestLookWeight)
                {
                    closestLookWeight = lookWeight;
                    primaryTarget = target;
                }
            }

            if (primaryTarget != null)
            {
                if ((lastPrimaryTarget != null) && (lastPrimaryTarget != primaryTarget) && (finalLookWeight > 0f))
                {
                    // Here we start a new transition because the player looks already to a target but
                    // we have found another target the player should look at
                    transitionToNextTarget = true;
                }
            }

            // The player is in a neutral look position but has found a new target
            if ((primaryTarget != null) && !transitionToNextTarget)
            {
                lastPrimaryTarget = primaryTarget;
                //finalLookWeight = Mathf.Lerp(finalLookWeight, closestLookWeight, Time.deltaTime * weightDamping);
                finalLookWeight = Mathf.Lerp(finalLookWeight, 1f, Time.deltaTime * weightDamping);
                float bodyWeight = finalLookWeight * .75f;
                animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
                animator.SetLookAtPosition(primaryTarget.transform.position);

                if (RightHandToTarget)
                {
                    Vector3 relativePos = primaryTarget.transform.position - transform.position;
                    Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
                    animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
                    animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
                    animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.7f * closestLookWeight);
                    animator.SetIKPosition(AvatarIKGoal.RightHand, primaryTarget.transform.position);
                }
            }

            // Let the player smoothly look away from the last target to the neutral look position
            if ((primaryTarget == null && lastPrimaryTarget != null) || transitionToNextTarget)
            {
                finalLookWeight = Mathf.Lerp(finalLookWeight, 0f, Time.deltaTime * weightDamping);
                float bodyWeight = finalLookWeight * .75f;
                animator.SetLookAtWeight(finalLookWeight, bodyWeight, 1f);
                animator.SetLookAtPosition(lastPrimaryTarget.transform.position);

                if (RightHandToTarget)
                {
                    Vector3 relativePos = lastPrimaryTarget.transform.position - transform.position;
                    Quaternion rotationtoTarget = Quaternion.LookRotation(relativePos, Vector3.up);
                    animator.SetIKRotationWeight(AvatarIKGoal.RightHand, finalLookWeight);
                    animator.SetIKRotation(AvatarIKGoal.RightHand, rotationtoTarget);
                    animator.SetIKPositionWeight(AvatarIKGoal.RightHand, finalLookWeight * 0.7f * closestLookWeight);
                    animator.SetIKPosition(AvatarIKGoal.RightHand, lastPrimaryTarget.transform.position);
                }

                if (finalLookWeight < lerpEndDistance)
                {
                    transitionToNextTarget = false;
                    finalLookWeight = 0f;
                    lastPrimaryTarget = null;
                }
            }

            // Show found object by the player
            if (primaryTarget != null)
            {
                text.text = primaryTarget.description;
            }
            else
            {
                text.text = "";
            }
        }
    }

    private void FixedUpdate()
    {
        int layerMask = 1 << 8;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(hand.transform.position, hand.transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(hand.transform.position, hand.transform.TransformDirection(Vector3.forward) * hit.distance, Color.red);
        }
        else
        {
            Debug.DrawRay(hand.transform.position, hand.transform.TransformDirection(Vector3.forward) * 1000, Color.yellow);
        }
    }
}

```

# Answer
There are a few things to fix:

* `hand.transform.TransformDirection(Vector3.forward)` is pointlessly complicated. Use `hand.transform.forward`.
* You haven't specified a duration for the line, so it will only last 1 frame. Here I use a duration of 5 seconds to ensure that you don't miss it. You'll want to remove that part once you figure out what's wrong, or you'll have red lines all over the place.
* Sometimes lines aren't visible because the line is too short. I multiply the length by 10 to hopefully make the line visible.
* Log a message to the console when the raycast hits, so we know whether the line is getting drawn at all.
* As suggested by DMGregory, draw a different color line when the raycast is *not* hitting (I chose blue) so we know where the hand is pointed at all times.

Code:

```
private void FixedUpdate()
{
    int layerMask = 1 << 8;

    RaycastHit hit;
    // Does the ray intersect any objects excluding the player layer
    if (Physics.Raycast(hand.transform.position, hand.transform.forward, out hit, Mathf.Infinity, layerMask))
    {
        Debug.Log("Raycast hit");
        Debug.DrawRay(hand.transform.position, hand.transform.forward * hit.distance * 10, Color.red, 5f);
    } else {
        Debug.DrawRay(hand.transform.position, hand.transform.forward * 10, Color.blue);
    }
}

```

I don't understand what you are saying about the yellow line. You should probably share the code that you're using to draw the yellow line.
> 0 votes

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


# Question
Title: Math: determining a proper procedural vector for sine-movement
**My Problem**

Suppose you have an object moving along the x-axis, wobbling up and down. Movement code might look like this:

```
x += 1;
y = Sin(x);
Move((x,y) * speed);

```

When I try to figure out a method to move my object along a sine wave, say diagonally, I run into trouble. I am not sure what kind of Vector math I use to calculate the appropriate Sine movement along a diagonal where both X and Y values must be altered.

The visual result would be the object bobbing up and down and sideways but still moving in its given direction.

**How do I enable sine movement along a diagonal?**

# Answer
> 2 votes
This can be achieved in multiple ways. The simplest is probably to calculate your vector as movement into the x-direction as you showed us in your question:

$$ v\_x = \begin{bmatrix}x\\\sin(x)\end{bmatrix} $$

Now you simply multiply the vector with a rotation matrix: $$ v = \begin{bmatrix}\cos(\alpha)&-sin(\alpha)\\\sin(\alpha)&\cos(\alpha)\end{bmatrix} \cdot s \cdot v\_x $$

Here, \\$s\\$ is the movement speed and \\$\alpha\\$ the angle between your x-axis and the vector pointing into the actual movement direction you want to move in.

However, it gets a little bit more complicated if you want the object to be able to change its direction. You can do this as follows:

$$ p\_{N+1} = p\_N + s \cdot v\_d + a \cdot \sin(w)\cdot v\_{offset} $$

\\$p\_N\\$ is the current position and \\$p\_{N+1}\\$ the next position. \\$v\_d\\$ is your current movement direction vector. It must be of length 1! So always normalize this vector. \\$v\_{offset}\\$ is a vector orthogonal to your movement direction. You can get it by multiplying it with a \\$90°\\$ rotation matrix. In 2d, you just need to exchange the x and y values of \\$v\_d\\$ and add a minus sign to one of both values. The variable \\$w\\$ is an arbitrary value that changes over time or while moving and \\$a\\$ is the amplitude of the sine wave.

The part \\$s \cdot v\_d + a \cdot \sin(w)\cdot v\_{offset}\\$ is the velocity vector that you wan to use in your `move` function.

This is basically the same as DMGregorys answer.

# Answer
> 2 votes
Just change your coordinate system.

```
// Replace your "x" axis with a vector that points along your diagonal.
Vector2 alongAxis = (diagonal_x, diagonal_y);

// Replace your "y" axis with a vector that points perpendicular to that.
Vector2 crossAxis = (-diagonal_y, diagonal_x);

// Move as before, using this new rotated coordinate system.
x += (alongAxis.x + Sin(t) * crossAxis.x) * speed;
y += (alongAxis.y + Sin(t) * crossAxis.y) * speed;

Move((x, y));

```

---
Tags: mathematics, rotation, movement, vector
---


title: Heuristic Cost in A* algorithm

text:
# Question
Title: Heuristic Cost in A* algorithm
I have been learning about the A\* path finding algorithm and I can't understand the heuristic cost in this algorithm. What is it and what is its use in the algorithm?

# Answer
It is merely a “wild guess about the distance left to goal.”

A guess that does not take into account any obstacles in the world.

So you use the shortest line between points.

It is the brown distance in the example below, used by the algorithm to compute the actual path in cyan.

It is best to underestimate the true distance, otherwise a path may be generated that is not the shortest.
> 1 votes

---
Tags: algorithm, ai, path-finding
---


title: How do I add an "offset" to LookAt?

text:
# Question
Title: How do I add an "offset" to LookAt?
I have created a Third Person Controller. The camera is behind the player:

I would like to make it so that the player aims at the mouse pointer position.

To do that, I use the following code to rotate the chest towards the position:

```
        var mousePos = Input.mousePosition;
        mousePos.z = 10; // Make sure to add some "depth" to the screen point
        var aim = Camera.main.ScreenToWorldPoint(mousePos);
        Chest.LookAt(aim);

```

The hands do not perfectly straightly point forwards, so I need to add an "offset" to the LookAt.

I tried this approach:

```
var mousePos = Input.mousePosition;
mousePos.z = 10; // Make sure to add some "depth" to the screen point
var aim = Camera.main.ScreenToWorldPoint(mousePos);
aim += new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0);

Chest.LookAt(aim);

```

Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself.

It does work, but when the model is rotated around the Y axis, something goes wrong: The offset is "wrong", it doesn't have the same effect.

This surprises me because all I do is rotate the entire model.

So I think this line is not correct:

```
aim += new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0);

```

Is this not the way to offset the LookAt results?

# Answer
If an easy-to-read way to offset the LookAt is required, then the following will work:

```
Chest.LookAt(aim);
Chest.rotation *= Quaternion.Euler(ChestAimCenterOffsetBecauseHandsDontPointStraightForward.x, ChestAimCenterOffsetBecauseHandsDontPointStraightForward.y, ChestAimCenterOffsetBecauseHandsDontPointStraightForward.z);

```

According to DMGregory's lesson however this is a more elegant and thus preferred solution with only 1 setter:

```
Quaternion lookAt = Quaternion.LookRotation(aim - Chest.position);
Quaternion correction = Quaternion.Euler(ChestAimCenterOffset);

Chest.rotation = lookAt * correction;

```

ps: I'm now using a Vector3 instead because I noticed that the up-down also needs an offset.
> 2 votes

---
Tags: unity, animation, rotation, third-person-view, inverse-kinematics
---


# Question
Title: Google admob ad shown after clicking multiple times
I'm using google admob to show rewarded video ads in my game. Once the game is over, the play video button is enabled. If the user clicks on that, a panel opens asking "would you like to revive the player by watching an ad". There are two options, one is to hit "ok" and the other to cancel "x". The issue is that the I have to click on "ok" multiple times for the ad to show. Sometimes the ad doesn't show at all no matter how many times I click on "ok" .Here is the code I have in adscript:

```
public class AdScript : MonoBehaviour
{

string App_ID = "ca-app-pub-123454545~12345678";

string Video_Ad_Id = "ca-app-pub-3940256099942544/5224354917";

private RewardedAd rewardedAd;

void Start()
{
    MobileAds.Initialize(App_ID);
}

public void RequestRewardBasedVideo()
{

    this.rewardedAd = new RewardedAd(Video_Ad_Id);
    AdRequest request = new AdRequest.Builder().Build();

    this.rewardedAd.LoadAd(request);
    this.rewardedAd.OnAdLoaded += HandleRewardedAdLoaded;

    this.rewardedAd.OnAdFailedToLoad += HandleRewardedAdFailedToLoad;

    this.rewardedAd.OnAdOpening += HandleRewardedAdOpening;

    this.rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;

    this.rewardedAd.OnUserEarnedReward += HandleUserEarnedReward;

    this.rewardedAd.OnAdClosed += HandleRewardedAdClosed;
}

public void ShowVideoRewardAd()
{
    if (this.rewardedAd.IsLoaded())
    {
        this.rewardedAd.Show();
    }
}

public void HandleRewardedAdLoaded(object sender, EventArgs args)
{
    MonoBehaviour.print("HandleRewardedAdLoaded event received");
}

public void HandleRewardedAdFailedToLoad(object sender, AdErrorEventArgs args)
{
    MonoBehaviour.print(
        "HandleRewardedAdFailedToLoad event received with message: "
                         + args.Message);
}

public void HandleRewardedAdOpening(object sender, EventArgs args)
{
    MonoBehaviour.print("HandleRewardedAdOpening event received");
}

public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
    MonoBehaviour.print(
        "HandleRewardedAdFailedToShow event received with message: "
                         + args.Message);
}

public void HandleRewardedAdClosed(object sender, EventArgs args)
{
    this.RequestRewardBasedVideo();
}

public void HandleUserEarnedReward(object sender, Reward args)
 {
    GameManager.instance.ReceiveReward();
 }
}

```

The function RequestRewardBasedVideo() is added to the play video button and the ShowVideoRewardAd() is added to the "ok" button. The test ads show properly but the issue is that I have to hit the ok button multiple times for the ad to display. I'm not sure why this is happening. Can someone please help?

# Answer
Ads can take awhile to load. Like, a long while. So long, in fact, that I usually start loading my first ad on app launch, and start loading the next ad immediately after the previous ad is finished playing.

My guess is that this:

```
public void ShowVideoRewardAd()
{
    if (this.rewardedAd.IsLoaded())
    {
        this.rewardedAd.Show();
    }
}

```

is just skipping over the call to Show over and over every time you tap the button, until the ad is actually loaded.

My suggestion is to not even show the option to watch an ad unless IsLoaded returns true. Alternatively, you can pop up a "please wait" dialog when the user taps to watch the video if IsLoaded is false, and wait for either HandleRewardedAdLoaded or HandleRewardedAdFailedToLoad is called.
> 0 votes

# Answer
I'll take a wild guess here (two guesses, actually).

The first guess is that the Ad framework is not yet completely initialized once you try to load your first ad. Based on the documentation, it seems you could pass a callback to the `MobileAds.Initialize();` that would be called once the initialization is done. You would need to wait until the initialization is properly completed before requesting your first ads. At first sight, the documentation is pretty bad regarding how to do this exactly, so I suggest you dig a bit further to find more about how you could achieve this.

The second guess is that you're trying to load an ad before you set the event handlers. If we take another look at the documentation, it appears that they place the calls to

```
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the rewarded ad with the request.
this.rewardedAd.LoadAd(request);

```

*after* they have set up the event listeners. The guess is that as soon as you ask it to "LoadAd", the framework fetches the list of listeners at that moment, and go do asynchronous stuff with it and calls the methods you had supplied at the moment of the call. There was no listeners at the moment of the call to LoadAd, so perhaps this is why you see "nothing happening" and you need to "tap multiple times", because on the first try, there is no listeners, and the listeners would be there only on the second time.
> 0 votes

---
Tags: unity, admob
---


# Question
Title: Entity component system: how and where store pointers to system resources or third-party lib's objects?
I'm migrating my game pet-project to ECS. I use C# (custom-made engine, not Unity). It goes pretty well, but one big thing is making me worry.

This is how and where to store pointers to system resources or third party libraries' objects?

For example, I have object with **Transform** and **RenderModel** component. **Transform** contains data like matrices, quaternions etc (like described in any ECS paper :) **RenderModel** contains path to FBX scene and some data how to render this model (materials, overrides, flags, scaling, etc).

For model rendering I use existing rendering library. To render the model I need to create object, add it to this library, update its transform if necessary and destroy it when I don't need to draw this model any more.

The question is where to store pointer to such rendering objects?

I see three approaches:

1. Any component that holds such resources implements methods `OnAdd` and `OnRemove` which are called when component added or removed respectively. On addition the component create lib's object and destroys it on removal. I've focused on this approach because it's pretty straightforward and simple to implement. Main drawback of such approach that I need to implement some kind of workaround to feed transformation to this models.
2. Systems are stateful and keep tracking of component addition and removal. When given combination of components is added (i.e. RenderModel and Transform) system that handle object drawing creates internal representation of the model and destroys when components are removed. Main drawback that I have no idea how efficiently track multiple component addition and removal.
3. Some kind of "imperative" approach. For each entity with RenderModel and Transform components system calls method like `DrawModel(...)`. At the end of the frame the internal representation is destroyed and created again on next frame. Such approach looks like most convenient approach from game logic view, but suffer from obvious performance issues, because rendering library might build internal structures, cache visibility data, use interleaved shadow maps etc. Furthermore, updating this systems in parallel threads obviously will become nightmare.

Same issues I've also encountered with physics library and FMOD sound, because such libs also offer some long-living objects (non-POD) and build internal data structures.

Could you suggest better approach to solve such issue?

**P.S. I use custom (made from scratch) engine (not Unity)**

# Answer
About option 1 (that's the one I suggest because I used a similar approach):

> Main drawback of such approach that I need to implement some kind of workaround to feed transformation to this models.

I don't think it's a "workaround". You need a function in a system that will propagate the physics simulation results to your Transform (for those objects simulated by the physics), a system that will propagate the other types of "animations" to the Transforms of those entities that are not moved my physics, and you'll need a function in a system that will propagate those Transforms to your RenderModel component.

Depending on how you do things, you can have your component just *hold* the pointer to your external libraries, while systems or other classes create them, at your convenience.

Keep in mind that an architecture pattern (ECS) is there to help you make your life easier, not to force you to do things in a certain way if they don't make sense to you, your project or your team, and there is no ECS police. Go with the approach that makes the most sense to you, and try to not get caught in analysis paralysis.
> 1 votes

---
Tags: architecture, rendering, game-loop, entity-component-system
---


# Question
Title: No local transform with skinned mesh with assimp?
I'm trying to add skeletal animation to my engine and I'm importing meshes with assimp, but I think I misunderstood the skinned mesh concepts (or don't understand assimp).

When I import a model, everything works fine, regardless of mesh hierarchy. I'm using collada files.

Here's how the model should look if it was imported correctly:

However, if I try to import skinned meshes, I get something really weird like this:

It happens because each mesh is imported without any local transform and everything stays in the wrong place/rotation.

But shouldn't the model stay the same as the first picture, because it should work even if it don't have a skinned mesh? Shouldn't the bone transform just be the offset matrix to convert from mesh space to bone space when using animation data to interpolate between key frames? I'm really confused.

I'm learning from Tutorial 38 - Skeletal Animation with Assimp.

# Answer
After some time i found out that the problem was actually the assimp collada importer. It worked fine if the object had only one mesh, but if it had multiple i'd have the problem you see in the print.

I solved it by switching to FBX
> 0 votes

---
Tags: opengl, c++, skeletal-animation, assimp
---


# Question
Title: Which version of Quake 2 source code do I need to compile to work with version 3.20 map packs?
I'm a big fan of `Quake 2` game. Recently I've decided to spend some of my free time for digging into the `Quake 2` src code. There are 2 versions of the full game code `3.19` and `3.21` (including the `game exe` as well as the `game dll`).

As regards to the Q2 Mission Packs the src files for both The Reckoning and Ground Zero are rather of verions 3.20 as the filename suggests (`xatrixsrc320.exe` and `roguesrc320.exe`)

My question is WHICH version of the `game exec` do I have to compile to use with the mission pack dlls? Is it better to use the `3.21` exe together with `3.20` of the xatrix & rogue dlls, or maybe the older `3.19` would be more appropriate?

# Answer
From looking at the changelog for 3.20 and 3.21:

> 12-22-2001, for source release under GPL licensing:
>
> * Tweaked linux/Makefile for easier build added linux/README-3.21-RELEASE
>
> 3.21 Changes:
>
> * Support for GL\_ARB\_multitexture added. This supports the new multitexture extensions and deprecates GL\_SGIS\_multitexture.
> * Linux OpenGL X11 handling completely rewritten. Support for XF86DGA Mouse and fullscreen resolution support added. Please see the README file for Linux about the new features of this handling.
>
> 3.20 Changes:
>
> * Fixed a network problem where and oversize packet could cause a client crash.
> * Fixed the long standing Quake2 bug of where you would occasionally spawn or teleport and find yourself either looking straight at the ceiling or down at the floor.
> * Changed it so that the function keys (F1 through F12) now get executed when depressed during demo playback or attract modes. This allows you to take screen shots (F12) during demos and other features. An example of other features is a fast forward for demos: alias +ff "timedemo 1" alias -ff "timedemo 0" bind f7 +ff This binding will cause the current demo playing to zip into timedemo mode while F7 is depressed, effectively acting like a fast forward key.
> * Wrong packaging of 3.19 patch. The Rogue CD has a 45k pak2 and vwep .md2 files in baseq2/players, but the 3.19 x86 patch we released has a 2.7MB pak2. 3.20 has a 45k pak2 and the vwep models go in baseq2/players.
> * VWep code has been added to Xatrix dll, new VWep models for the Xatrix specific weapons (Ion Ripper and Phalanx) have been included.
> * Rogue Linux game library was wrong version and had some unlinked symbols, this has been corrected.
> * Occasional error of: "D\_SCAlloc: bad cache width 16384" in software renderer. This had to do with surfaces to SURF\_FLOWING and were transparent. This has been fixed in the refs now so flowing transparent textures now works.
> * \[Unix\] Net\_ErrorToString calls were wrong, was using %i and not %s resulting in random numbers being printed for error messages.
> * Color shell mixing restored to the same blends as previous versions. This was changed in 3.19 for the new color shells the Rogue mission pack introduced.
> * Fixed a possible server crash in the new "playerlist" command.
> * Fixed a case where a person joining a server could be invisible (left over setting of SVF\_NOCLIENT from previous spectator).
> * Invalid pak files no longer cause a crash and are just ignored
> * Fixed a 3.19 bug where linked models (modelindex2) who's modelindex was greater than 0x7f causes the wrong model to be drawn (in some cases, the world would be drawn twice). This was the cause of many of the "extreme" frame lag people were seeing in 3.19 on servers using old-style VWep code.
> * Linux: Complete rewrite of the OpenGL library handling. This was needed to cleanly integrate OpenGL extension checking. Linux now supports extensions such as multitexture and better dynamic loading of libraries. It's cleaner now in that you don't have to preload hack stuff to use the 3DFX Miniport rather than libMesa3D. The Linux version now uses the gl\_driver to specify the 3D library to dynamically load. For example, to use the lib3dfxgl.so miniport, one would now use: ./quake2 +set vid\_ref gl +set gl\_driver lib3dfxgl.so This change fixes several bugs that were apparant in the older method, such as a segfault occasionally when connecting to a server with a different game directory. The vid menu in the Linux version has been changed to reflect the new options, the current list of supported video drivers are now: software, software X11, Mesa 3-D 3DFX, 3DFXGL Miniport, OpenGL glX, and Mesa 3-D glX,
> * Railgun shots now go through gibs as well as other players.
> * New server variable, "needpass" that can been seen with server browser tools such as GameSpy. This variable indicates whether a password or spectator password is needed to get onto a server. Bit 0 is password and bit 1 is spectator password.
> * Quake2 will no longer look for gamex86.dll in the main Quake2 directory. It will always load out of the game directory first.
> * Players joining a server during an intermission are now moved to the intermission position.
> * The "logfile" cvar has been extended with the following values: 0 - don't log (default) 1 - overwrite qconsole.log and use buffered writes 2 - overwrite qconsole.log and flush write every line 3 - append to existing qconsole.log and flush write every line
> * Several minor bug fixes to the Rogue mission pack gamex86.dll
> * Linux: Rebuild of Rogue mission pack shared library to correct some dynamic symbol errors (is NAN errors).

3.20 seems to include some very desirable fixes, whereas the 3.21 changes should not affect game compatibility. 3.21 therefore appears to be the version you should use.
> 2 votes

---
Tags: c++, windows, quake2
---


# Question
Title: Updating the position of a prefab in Unity for A* pathfinding
I am trying to use Aron Granberg A\* pathfinding project in my game. I am very new to Unity, so I am having some trouble figuring out how to instantiate multiple enemies from a prefab that will seek out my player. I am unable to set the player object from the scene as the target, since prefabs cannot take in scene objects. However, if I use the player prefab as the target, the enemies will only go toward the starting position of the player. Is there any way to update the prefab position as the player instance moves? Or is there a better way of doing this? I want this to be a top-down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance. Any help would be greatly appreciated. Thank you!

# Answer
> 2 votes
FYI Unity has built-in pathfinding using NavMesh .

It sounds like you're confusing the prefabs with scene instances. What you want is something like this:

```
[SerializeField] private Player playerPrefab;
[SerializeField] private Enemy enemyPrefab;
private Player player;

void Start() {
    player = Instantiate(playerPrefab);
}

void SpawnEnemy() {
    var enemy = Instantiate(enemyPrefab);
    enemy.target = player;
}

```

Here we save the actual player instance to a variable, and we set the enemy's target to the actual player instance, rather than the player's prefab.

> I want this to be a top-down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance.

It *does* make sense to set the target for each individual enemy instance. You have to set the target somehow. Setting the target does not take a lot of code and is not going to negatively impact performance.

---
Tags: unity, path-finding
---


# Question
Title: How do I interpolate an object from point A to B such that it accelerates, overshoots, and bounces back to target position?
# How The Game Works

You grab and drag an object around. Once you let go, it interpolates to a certain, variable position, and that's what I'm trying to do here.

# Problem Description

I'm talking about vectors, but simplifying that to ordinary numbers for the sake of an example, if A is 0 and B is 1, the object would go something like this:

1. 0.0
2. 0.2
3. 0.5
4. 0.9
5. 1.3
6. 0.9
7. 1.1
8. 1.0

# What I've Tried

```
private IEnumerator GoTo(Vector2 endPosition) {
    float elapsed = 0;
    float duration = 1f;

    while (elapsed <= duration) {
        transform.position = Vector2.LerpUnclamped(transform.position, endPosition, animCurve.Evaluate(elapsed / duration));
        distance = CalculateDistance(transform.position, endPosition);
        elapsed += Time.deltaTime;
        yield return new WaitForEndOfFrame();
    }
}

```

Where **animCurve** is:  The highest point is approx. 1.3, and the plot converges to 1.0 from there.

### Result

This doesn't work at all. Unless something's wrong with Unity's `Vector2.LerpUnclamped()`, I'm lost.

# Answer
> 2 votes
A few small fixes:

1. Cache your initial position, and lerp from there to your end, to avoid a feedback loop where `transform.position` is being used to modify itself.
2. Advance your elapsed before updating position - that way you finish the loop at your end position, rather than one frame before your end position.
3. Yield return null to resume next frame with next frame's delta, not at the end of this frame.

All together:

```
private IEnumerator GoTo(Vector2 endPosition) {
    float elapsed = 0;
    float duration = 1f;

    Vector2 startPosition = (Vector2)transform.position;

    while (elapsed <= duration) {
        elapsed += Time.deltaTime;
        float t = animCurve.Evaluate(elapsed / duration));
        transform.position = Vector2.LerpUnclamped(startPosition, endPosition, t);
        distance = CalculateDistance(transform.position, endPosition);
        yield return null;
    }
}

```

---
Tags: unity, interpolation, lerp
---


# Question
Title: How do you disable frame skips in a game, in SFML preferably
by frame skip off i mean that the game should just slow down if the fps drops, just like in terraria, i got this code currently and want to implement it to it:

```
static class Globals
{
    static public Time dt = new Time();
    static public Vector2f Friction
    {
        get
        {
            return new Vector2f(2 * dt.AsSeconds(), 0);
        }
    }
}

class Player
{
        private void StartMoving(int _direction)
    {
        moving = true;
        direction = _direction;
        heldfor =  1;
        Move(direction);
    }
    public void Move(int _direction)
    {
        if(!moving)
        {
            StartMoving(_direction);
            return;
        }
        if(direction == _direction)
        {
            if(heldfor < heldforlimit) heldfor++;
            Velocity += new Vector2f(((speed * (heldfor / 10f)) * direction) * Globals.dt.AsSeconds(), 0);
        }
        else
        {

            direction = _direction;
            heldfor /= 2;
            Velocity = new Vector2f(Velocity.X / 1.5f, Velocity.Y);
            if (heldfor < heldforlimit) heldfor++;
            Velocity += new Vector2f(((speed * (heldfor / 10f)) * direction) * Globals.dt.AsSeconds(), 0);
        }

    }
    public void StopMoving()
    {
        moving = false;
        heldfor = 1;
    }

    public void Update(Time dt)
    {
        if(!moving)
        {
            if(Math.Abs(Velocity.X) - Globals.Friction.X < 0)
            {
                Velocity.X = 0;
            }
            else
            {   // i really should make this direction independent and apply direction at end of the update
                Velocity.X = Velocity.X > 0 ? Velocity.X - Globals.Friction.X : Velocity.X + Globals.Friction.X;
            }
            if (Math.Abs(Velocity.X) <= velocitySnapX) Velocity.X = 0;
            if (Math.Abs(Velocity.Y) <= velocitySnapY) Velocity.Y = 0;
        }
        if (Math.Abs(Velocity.X) > XMaxvel) Velocity.X = XMaxvel * direction;
        if (Math.Abs(Velocity.Y) > YMaxvel) Velocity.Y = YMaxvel * direction;
        Position += Velocity;
    }
}

class Program
{
    Player player = new Player();
    while(game.isrunning) // this is made up as the genuine code is too messy
    {
                    if (Keyboard.IsKeyPressed(Keyboard.Key.Right))
            {
                player.Move(1);
            }
            if (Keyboard.IsKeyPressed(Keyboard.Key.Left))
            {
                player.Move(-1);
            }
            window.Clear(Color.White);
            window.Draw(player);
            player.Update(Globals.dt);
            window.DispatchEvents();
            window.Display();
            window.SetView(mainview);
            Globals.dt = deltaclock.Restart();
    }
}

```

# Answer
> 1 votes
A way to do this is to enforce a maximum cap on your time delta.

Building on Martin Sand's example:

```
// Get the time delta since last frame.
sf::Time dt = clock.restart();

// Convert to seconds, and clamp to your maximum time step.
float dtAsSeconds = std::min(dt.asSeconds(), 1f/30f);

```

That way, even if a frame runs really long, the game behaves as though a smaller amount of time passed, slowing down the action relative to wall clock time, rather than jumping ahead to try to catch up.

This can layer on top of a fixed timestep solution as well, leading you to perform fewer fixed ticks this frame to ensure you don't advance the simulation state too far in a single rendered frame.

# Answer
> 0 votes
I always recommend to start coding with the time step. The time step is the time between the different frames. There are several ways to handle this. The Fix Your Timestep web page summarizes them perfectly. It is kind of a reference.

Please find below same code sample. Code is for Linux but should also compile and work in Windows.

```
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    window.setFramerateLimit(60);

    // Timing
    sf::Clock clock;

    while (window.isOpen())
    {
        // Update the delta time to measure movement accurately
        sf::Time dt = clock.restart();

        // Convert to seconds to do the maths
        float dtAsSeconds = dt.asSeconds();

        // For debuging, print the time to the terminal
        // It illustrates the differences
        std::cout << "Time step: " << dtAsSeconds << '\n';

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

```

---
Tags: algorithm, sfml, timestep
---


# Question
Title: Spawning prefab on touch after previous spawn(s) had been destroyed
I wrote a script which pawns an object (instantiated prefab) each time the player touches the screen.

The maximum number of these spawned objects active in the scene at once is 3, and when they are not visible they will be destroyed. I need these prefabs to be able spawn again after they had been destroyed.

I tried this but it does not work...

This script is added to a game object called "canCreator" in my scene hierarchy:

```
public class CreatingCan: MonoBehaviour
{
    public GameObject Can;
    public int numberOfCans;
    public bool canSpawn = true;

    private void Start()
    {
        numberOfCans = 0;
    }
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            Vector2 TouchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            if (touch.phase == TouchPhase.Began && canSpawn == true)
            {
                if (Instantiate(Can, TouchPosition, Quaternion.identity))
                {
                    numberOfCans++;
                }
            }
        }

        if (numberOfCans >= 3)
        {
            canSpawn = false;
        }

    }

}

```

This script is on my can prefab:

```
public class fallingCan : MonoBehaviour
{
    CreatingCan CC;
    private void Update()
    {

        if (transform.position.x < Camera.main.transform.position.x - 10)
        {
            Destroy(gameObject);
               CC.numberOfCans--;
        }
    }
}

```

# Answer
> 0 votes
A simple trick I like to use is introduce a self-counting object script:

```
public class CountedObject : MonoBehaviour {

    static int _count;

    void OnEnable() { _count++; }

    void OnDisable() { _count--; }

    public int GetActiveCount() { return _count; }
}

```

Then your spawner can look like...

```
public class CreatingCan: MonoBehaviour
{
    public CountedObject canPrefab;
    public int spawnLimit = 3;
    public bool canSpawn = true;

    void Update()
    {
        // Don't spawn more if we've disabled spawning, or are at/above our limit.
        if (!canSpawn || canPrefab.GetActiveCount() >= spawnLimit)
            return;

        // Check all touches, not just the first one, so it works even if you
        // hold one finger on the screen, and tap with another.
        for (int i = 0; i < Input.touchCount; i++) {
            var touch = Input.GetTouch(i);
            if (touch.phase != TouchPhase.Began)
                continue; // Skip any old touches.

            Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            Instantiate(canPrefab, touchPosition, Quaternion.identity)

            // Abort if we hit our limit, even if there are still more touches.
            if (canPrefab.GetActiveCount() >= spawnLimit)
                break;
        }
    }
}

```

# Answer
> 0 votes
Here's your problem:

```
if (numberOfCans >= 3)
{
    canSpawn = false;
}

```

You never set `canSpawn` to true after this.

Maybe what you wanted is `canSpawn = (numberOfCans >= 3)`. This will update `canSpawn` each frame.

---
Tags: unity, 2d, spawning
---


# Question
Title: How does re-glBufferData()'ing interact with glVertexAttribPointer?
I understand the basic sequence: glGenBuffers() creates a "buffer object name," glBindBuffer() creates the actual buffer object (as well as binding the name), glBufferData() "creates and initializes a buffer object's data store," and glVertexAttribPointer() sets the format of the buffer data, as well as saving the buffer object binding as part of vertex attrib array state.

The tricky thing that I'm unsure of is if the glVertexAttribPointer() stuff remains valid if the the "buffer object data store" (but not the buffer object itself) is blown away by a new call to glBufferData(). I'm aware that this isn't usually a good idea - use glBufferSubData() when just rewriting buffers - but glBufferData() seems like the only option if it needs to be resized. Plus, I'm just curious.

The reference pages make it sound like it could go either way - in particular (https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml):

> If *pointer* is not NULL, a non-zero named buffer object must be bound to the GL\_ARRAY\_BUFFER target (see glBindBuffer), otherwise an error is generated. *pointer* is treated as a byte offset into the buffer object's data store. The buffer object binding (GL\_ARRAY\_BUFFER\_BINDING) is saved as generic vertex attribute array state (GL\_VERTEX\_ATTRIB\_ARRAY\_BUFFER\_BINDING) for index *index*.
>
> When a generic vertex attribute array is specified, *size*, *type*, *normalized*, *stride*, and *pointer* are saved as vertex array state, in addition to the current vertex array buffer object binding.

It seems like both the byte offset and the buffer object binding could remain valid, even if the data store was replaced by something different. But I could also see it being implemented such that at the time of the call, the binding captures a *specific* pointer into the data store, which becomes invalidated if the data store is replaced. Neither way seems to be precluded by the wording.

# Answer
It appears that glVertexAttribPointer() bindings remain valid, even after subsequent calls to glBufferData(). I determined this by trying it, which isn't 100% proof - it could just be working only in this implementation (NVidia drivers, in my case).

However, with an error message callback and debug mode on, I get the following message on the second call to glBufferData(), which strongly suggests that this situation is expected/designed for:

```
[LWJGL] OpenGL debug message
    ID: 0x20071
    Source: API
    Type: OTHER
    Severity: NOTIFICATION
    Message: Buffer detailed info: Buffer object 1 (bound to GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (0), GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB (1), and GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations.
```

The first two bindings represent my two calls to glVertexAttribPointer(), and aren't present in the message that gets logged the first time I call glBufferData().
> 0 votes

---
Tags: opengl
---


# Question
Title: Is it possible to move a parent object independent of the child object
I need to be able to move a Parent Object without moving the Child Objects.

# Answer
> 1 votes
No. If you do not want a child to move with its parent, then do not make it a child of that parent. Parenting means "I want this child object to move with its parent".

If that's not the behaviour you want, then this is not the hammer for your particular nail, and you should look for a different relationship that isn't transformation parenting.

---
Tags: unity
---