# Question
Title: Do retail games use "inversion of control" and "dependency injection"?
Many of the more diligent software developers I know are moving to inversion of control and dependency injection to handle references to objects. Coming from a Flash games perspective I don't know all the ins and outs of AAA studios, so: are these used in the retail game world?

# Answer
You call it 'diligent software development', I call it 'painful overengineering'. That's not to say that inversion of control is bad - in fact, the basic definition of it is good - but the proliferation of entire frameworks and methods of working to achieve all this is little short of insane, especially combined with the way people are trashing perfectly good and clean interfaces in order to be able to inject interchangeable components that 99% of the time you'll never interchange. It's the sort of thing that could only originate from the Java enterprise environment and I'm glad it doesn't have as much of a foothold elsewhere.

Often the argument is that even if you don't interchange components, you want to be able to test them in isolation with mock objects and the like. However, I'm afraid I will never buy the argument that it's worth bloating and complicating an interface in order to be better able to test it. Testing proves one thing only - that your tests work. Clean and minimal interfaces on the other hand go a long way towards **proving** that your code works.

So, the short answer: yes, but not in the way you're thinking. Sometimes, when you need interchangeable behaviour, you'll pass in an object to a constructor that dictates part of the new object's behaviour. That's about it.
> 41 votes

# Answer
**Strategy Pattern**, **Composition**, **Dependency Injection**, are all very closely related.

Since the Strategy Pattern is a form of Dependency Injection, if you take a look at engines like Unity for example they are completely based off this principle. Their use of Components(Strategy Pattern) is deeply embedded into their whole engine.

One of the main benefits aside from reuse of components is to avoid the dreaded deep class hierarchies.

Here is an article by **Mick West** who talks about how he introduced this type of system into the **Tony Hawk** series of games by Neversoft.

**Evolve Your Hierarchy**

> Up until fairly recent years, game programmers have consistently used a deep class hierarchy to represent game entities. The tide is beginning to shift from this use of deep hierarchies to a variety of methods that compose a game entity object as an aggregation of components...
> 18 votes

# Answer
There seems to be a lot of confusion about the Inversion of Control (IoC) pattern. A number of people have equated it with the Strategy Pattern or a Component Model, but these comparison don't really capture what IoC is about. IoC is really about how a dependency is obtained. Let me give you an example:

```
class Game {
    void Load() {
        this.Sprite.Load(); // loads resource for drawing later
    }
}

class Sprite {
    void Load() {
        FileReader reader = new FileReader("path/to/resource.gif");
        // load image from file
    }
}

```

In the above it's clear that `Sprite.Load` has a dependency on a `FileReader`. When you want to test the method you need the following:

1. A file system in place
2. A test file to load from the file system
3. Ability to trigger common file system errors

The first two are obvious, but if you want to ensure that your error handling works as expected you really need #3, too. In both cases you've potentially slowed your tests down quite a bit as they now need to go to disk and you've likely made your testing environment more complicated.

The goal of IoC is to decouple the use of behavior from its construction. Note how this differs from the Strategy pattern. With the Strategy pattern the goal is to encapsulate a re-usuable chunk of behavior so that you can easily extend it in the future; it has nothing to say about how strategies are constructed.

If we were to rewrite the `Sprite.Load` method above we would likely end up with:

```
class Sprite {
    void Load(IReader reader) {
        // load image through reader
    }
}

```

Now, we have decoupled the construction of the reader from its use. Therefore, it's possible to swap in a test reader during testing. This means that your testing environment no longer needs a file system, test files, and can easily simulate error events.

Note that I did two things in my rewrite. I created an interface `IReader` which encapsulated some behavior -- i.e. implemented the Strategy pattern. In addition, I moved the responsibility for creating the right reader to another class.

Maybe we don't need a new pattern name to describe the above. It strikes me as a mix of the Strategy and Factory patterns (for IoC containers). That being said, I'm not sure on what grounds people are objecting to this pattern as it's clear that it solves a real problem, and, certainly, it's not obvious to me what this has to do with Java.
> 15 votes

# Answer
I'm writing this at a time when the accepted answer is by a contributor who strongly opposes the concept and I wish to provide a different view:

Dependency injection is indeed not widely used in game development.

In my humble opinion, the reason for this is simply that most game developers are self-taught and know very little about software architecture. Most just wing it or even grow attached to hacks such as the singleton anti-pattern.

Dependency injection is, in games as well, a useful technique that will vastly improve a project's structure:

* Reduce inter-system dependencies because these are accessed through interfaces
* Result in easier-to-understand code because you'll *design* interfaces to your systems rather than have them happen by accident
* Reduce complexity because each system can be understood on its own and accesses other systems only by intentional interface
* Improve testability by allowing modules to be isolated via mocks (stand-in dummies for the actual dependencies)
* Better testabilityu allows more tests, thus making it easier to refactor and reuse
* The resulting smaller code units are easier to maintain and help uphold the single responsibility principle

You can find IoC add-ons for Unity (i.e. Zenject), Godot and Xenko game engine.

---

Also relevant is that most games eventually find the need to have some kind of *services* available throughout the game, whether it's for querying time-of-day or weather in the game world, enumerating save slots or reading the difficulty settings. And most game developers then reinvent the wheel:

Unity developers rely on static variables in `DontDestroyOnLoad` classes or a master scene that's always remains loaded (or Zenject).

Godot developers have "AutoLoad" scenes that are always loaded before any other scene. Services that should be available throughout the game can be placed in that scene.

Unreal developers extend the GameInstance class to add game-wide services (and the engine offers some services of its own).

---

*Source: being a full-time software developer (visualuation / real time) for 25 years & moonlighting game developer for 30 years.*
> 9 votes

# Answer
I would say that it is one tool among many, and it is used on occasion. As tenpn said any method that introduces vtables (and generally any extra indirection) can have a performance penalty, but this is something that we should only worry about for low-level code. For high-level structural code that isn't really an issue, and IoC can have positive benefits. Anything to reduce dependencies between classes and make your code more flexible.
> 4 votes

# Answer
Not in my experience. Which is a shame, as games code needs to be very adaptable, and these approaches would definitely help.

However it must be said that both methods could, in C++, introduce virtual tables where there were none before, bringing with them an appropriate performance hit.
> 2 votes

# Answer
Gotta agree with Kylotan on this one. "Dependency injection" is an ugly Java solution to an ugly Java conceptual flaw, and the only reason anyone's looking at it in other languages at all is because Java's becoming a first language for a lot of people, when it really shouldn't.

Inversion of control, on the other hand, is a useful idea that's been around for a long time, and is very helpful when done right. (Not the Java/Dependency Injection way.) In fact, you probably do it all the time if you're working in a sane programming language. When I first read up on this whole "IOC" thing everyone was buzzing about, I was completely underwhelmed. Inversion of Control is nothing more than passing a function pointer (or method pointer) to a routine or object in order to help customize its behavior.

This is an idea that's been around since the 1950s. It's in the C standard library (qsort comes to mind) and it's *all over the place* in Delphi and .NET (event handlers/delegates). It enables old code to call new code without needing to recompile the old code, and it gets used all the time in game engines.
> 2 votes

# Answer
I'm not a professionnal game dev, and only tried implementing IoC in C++ once, so this is just speculating.

However, I suspect game developers's would be suspicious about IoC because it means :

1/ designing lots of interfaces and lots of small classes

2/ having pretty much every function call being lately bound

Now, it might be a coincidence, but both tend to be a little bit more complicated and/or problematic for performances in C++ (which is widely used in game, isn't it ?) than in Java , where IoC became widespread (Probably because it was relatively easy to do, help people design saner object hierarchies, and because some believed it could turn writing an a application in Java into writing an application in XML, but that's another debate :P)

I'm interested in the comments if that does not make any sense at all ;)
> 1 votes

---
Tags: software-engineering, design-patterns, dependency-injection
---


title: glsl wrong light direction

text:
# Question
Title: glsl wrong light direction
I'm practicing the Phong lighting model with glsl, and here's my shaders: vertex shader:

```
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;
layout (location = 2) in vec3 aNormal;

out vec2 TexCoord;
out vec3 LightColor;
uniform mat4 model;
layout (std140) uniform coord_mats {
    mat4 view;
    mat4 projection;
    vec3 lightPos;
    vec3 lightColor;
};

void main()
{
    vec3 vertex_position = vec3(model * vec4(aPos, 1.0));
//    vec3 vertex_position = vec3(view * model * vec4(aPos, 1.0));
    vec3 vertex_normal = normalize(vec3(model * vec4 (aNormal, 1.0)));
//    vec3 vertex_normal = normalize(vec3(view * model * vec4 (aNormal, 1.0)));
    vec3 light_position = vec3(vec4(lightPos, 1.0));
//    vec3 light_position = vec3(view * vec4(lightPos, 1.0));
    vec3 light_dir = normalize(light_position - vertex_position);
    float diff = max(dot( light_dir,vertex_normal), 0.0);
    vec3 diffuse = diff * lightColor;
    vec3 ambient = 0.1 * lightColor;
    LightColor = diffuse + ambient;

    gl_Position = projection * view * model * vec4(aPos, 1.0);
    TexCoord = vec2(aTexCoord.x, aTexCoord.y);
}

```

fragment shader:

```
#version 330 core
out vec4 FragColor;

in vec2 TexCoord;
in vec3 LightColor;
// texture sampler
uniform sampler2D texture1;

void main()
{
    FragColor = vec4(LightColor,1.0) * texture(texture1, TexCoord);
}

```

The diffuse light works right, that is, faces which are facing to the light source, are bright, when backing the light source, they are dark(basically ambient color).

Now I want to calculate the specular light, in order to get the camera position for free, I changes the coordinate to camera view coordinate(using the commented code, just multiply the view matrix to the vertex position, normal and light position), but weird things happened: all faces which are facing the light is dark, all faces which are backing to the light is bright.

How could this happened?

# Answer
Sorry I cannot put a comment yet, however, I noticed that you have 'w' set to 1 in your normal i.e. it would be translated as well. It might have caused this issue.
> 1 votes

---
Tags: shaders, glsl
---


# Question
Title: How to create a LUT from original and processed images (not perfectly the same)?
I would like to create a certain LUT for my game in Unity. The usual way would be to take a screenshot in your game, process this screenshot in an image editor like Photoshop / GIMP and then calculate the LUT from that.

I would like to re-create the LUT used in the movie Memories of Murder.

I do not have access to the un-processed film material, so I can not automatically create the LUT as I would normally do with the above approach.

The closest comparison between the original colors and the processed version that I could get were these images.

I captured them from the making of.

Is there any way to create a LUT from these 2 images somehow even if they don't show exactely the same moment?

# Answer
> 1 votes
I found a good solution in this software: "Image 2 LUT".

Here are my results, I'm really happy.

Right after loading both images, the software created a LUT for me, and it looked somewhat ok. Not perfect, but already lots better then what I tried with a manual approach in GIMP.

I played around 10 minutes with the sliders of "Image 2 LUT" without really knowing what I did, and I finally came up with something that I would consider *really close* to the original LUT.

---
Tags: unity, color, post-processing
---


# Question
Title: How to get the fingerID (Touch) that is pressing a specific UI button. (Unity)
I want to displace a button along with the screen position that is pressing on it.

However, having multiple touches at the same time results in wanky behaviour.

So I want to limit the button's movement to the touch that started it.

I'm aware of the PointerEventData.pointerId but I couldn't figure out how to use it.

# Answer
Shortly after, I figured the problem was that I was not implementing the IPointerDownHandler interface causing the IPointerUpHandler to not work.

And this is the final script:

```
using UnityEngine;
using UnityEngine.EventSystems;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
{
    [SerializeField] RectTransform joystickBG, joystickHandle;
    [HideInInspector] public Vector2 moveAxis;
    [Range(0, 2)] [SerializeField] float handleLimit;

    private void Awake()
    {
#if !(UNITY_ANDROID || UNITY_IOS) // || UNITY_EDITOR
        Destroy(gameObject);
#endif
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        moveAxis = joystickHandle.anchoredPosition = Vector2.zero;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        moveAxis = ((Vector3)InputMaster.getPointerFromId(eventData.pointerId).position - joystickBG.position);
        joystickHandle.position = joystickBG.position + Vector3.ClampMagnitude(moveAxis, joystickBG.rect.width / 2 * handleLimit);
        moveAxis.Normalize();
    }

    public void OnDrag(PointerEventData eventData)
    {
        moveAxis = ((Vector3)InputMaster.getPointerFromId(eventData.pointerId).position - joystickBG.position);
        joystickHandle.position = joystickBG.position + Vector3.ClampMagnitude(moveAxis, joystickBG.rect.width / 2 * handleLimit);
        moveAxis.Normalize();
    }
}

```
> 1 votes

---
Tags: events, touch, unity-ui
---


# Question
Title: The rightmost part of the game screen is truncated in HTML
I created a game that, when I play it in Unity, looks like this:

But when I build it in WebGL, the rightmost part of the screen (with the red player character in it) is truncated:

Play it in-browser on itch.io to confirm. It looks the same when I open the HTML file locally, so the problem is with the WebGL version and not with itch.

Only when I click the "full screen" button, the rightmost part is shown.

What am I doing wrong?

# Answer
> 2 votes
Your WebGL export is using a different aspect ratio than the one you're using in your editor.

The WebGL viewport is 960x600, an 8:5 aspect ratio, where the width is 1.6 times the height.

Your editor viewport is 650x366, so the width is 1.776 times the height.

By default, Unity scales the view to preserve the vertical axis, so you see the same height of your scene in both views. But because your editor view is wider, you're able to see more off to both the left & right sides.

So, some possible fixes you can use:

* Change your export aspect ratio / target resolution to reflect your intended cropping.
* In the Resolution drop-down at the top-left of your Game window in the editor, choose the resolution or aspect ratio you intend to build for, so you can design your scene with the final cropping in mind.
* Add a script to your camera to adjust the vertical extents, rather than the horizontal extents, or add letterboxing/pillarboxing to match to your desired aspect ratio even when the screen/browser window is a different shape.

---
Tags: unity, webgl, aspect-ratio
---


# Question
Title: Add parabola curve to straight MoveTowards() movement
I have some units shooting arrows, right now they move in a straight line to the target. I want them to move like a real arrow, i.e using a parabola curve. However I don't want to use physics.

The math I need to do seems to be beyond me, I've tried to convert 2d solution I found online and other semi-similar solution with no luck.

My current straight movement:

```
private void Update()
{
    var nextPos = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
    transform.LookAt(nextPos, transform.forward);
    transform.position = nextPos;

    if (Vector3.Distance(nextPos, target) < .1f)
        Arrived();
}

```

An example of a 2d version I tried to replicate: Here.

# Answer
```
public float speed;
public Vector3 target;
public float arcHeight;

Vector3 _startPosition;
float _stepScale;
float _progress;

void Start() {
    _startPosition = transform.position;

    float distance = Vector3.Distance(_startPosition, target);

    // This is one divided by the total flight duration, to help convert it to 0-1 progress.
    _stepScale = speed / distance;
}

void Update() {
    // Increment our progress from 0 at the start, to 1 when we arrive.
    _progress = Mathf.Min(_progress + Time.deltaTime * _stepSize, 1.0f);

    // Turn this 0-1 value into a parabola that goes from 0 to 1, then back to 0.
    float parabola = 1.0f - 4.0f * (_progress - 0.5f) * (_progress - 0.5f);

    // Travel in a straight line from our start position to the target.
    Vector3 nextPos = Vector3.Lerp(_startPosition, target, progress);

    // Then add a vertical arc in excess of this.
    nextPos.y += parabola * arcHeight;

    // Continue as before.
    transform.LookAt(nextPos, transform.forward);
    transform.position = nextPos;

    // I presume you disable/destroy the arrow in Arrived so it doesn't keep arriving.
    if(progress == 1.0f)
        Arrived();
}

```
> 2 votes

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


# Question
Title: Making a crosshatching effect in Unity Shader Graphs
I'm learning Shader Graph and am trying to experiment with toon shading effects. One thing I'd love to do is make a traditional art styled crosshatching effect either inside shadows or at the edge of shadows. However, I'm lost as to how to do that. I have a sample crosshatch texture I can use as a texture2D but I'm unsure how to use this as an input in shadows and to which nodes to hook it up to. I'm very new to dabbling in shaders so I'd appreciate any tips.

# Answer
> 5 votes
Usually I approach this kind of effect as a post-process image effect:

* Render the wholes scene with normal lighting, benefitting from all of Unity's built-in shading features that you might want to use.
* Read the resulting image as a texture, and compute the brightness of each pixel.
* Clamp that brightness into ranges, one for each pair of consecutive hatching swatches in your texture.
* Sample from your swatch texture twice, using screenspace UV coordinates. Once for the swatch at the dark end of the range, and once for the swatch at the bright end.
* Interpolate between the two swatch samples according to your brightness within the range.
* Output the result back into the rendering pipeline for any subsequent passes.

Using the scriptable render pipeline, you need to define a Renderer Feature that will inject this new pass into the pipe. Based on the example here, we can write something like this:

```
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

public class ImageEffectFeature : ScriptableRendererFeature
{
    class CustomRenderPass : ScriptableRenderPass
    {
        private RenderTargetIdentifier source { get; set; }
        private RenderTargetHandle destination { get; set; }
        public Material material = null;
        RenderTargetHandle _temporaryColorTexture;

        public CustomRenderPass(Material material) {
            this.material = material;
        }

        public void Setup(RenderTargetIdentifier source, RenderTargetHandle destination) {
            this.source = source;
            this.destination = destination;
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get("_OutlinePass");

            RenderTextureDescriptor opaqueDescriptor = renderingData.cameraData.cameraTargetDescriptor;
            opaqueDescriptor.depthBufferBits = 0;

            if (destination == RenderTargetHandle.CameraTarget) {
                cmd.GetTemporaryRT(_temporaryColorTexture.id, opaqueDescriptor, FilterMode.Point);
                Blit(cmd, source, _temporaryColorTexture.Identifier(), material, 0);
                Blit(cmd, _temporaryColorTexture.Identifier(), source);

            } else Blit(cmd, source, destination.Identifier(), material, 0);

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }

        public override void FrameCleanup(CommandBuffer cmd)
        {
            if (destination == RenderTargetHandle.CameraTarget)
                cmd.ReleaseTemporaryRT(_temporaryColorTexture.id);
        }
    }

    public Material material;
    CustomRenderPass m_ScriptablePass;

    public override void Create()
    {
        if(material == null) {
            Debug.LogWarning("Missing Image Effect Material", this);
            return;
        }
        m_ScriptablePass = new CustomRenderPass(material);

        m_ScriptablePass.renderPassEvent = RenderPassEvent.BeforeRenderingPostProcessing;
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
    {
        if (material == null) {
            return;
        }
        m_ScriptablePass.Setup(renderer.cameraColorTarget, RenderTargetHandle.CameraTarget);
        renderer.EnqueuePass(m_ScriptablePass);
    }
}

```

This will let you select the renderer asset you're using and choose "Add Renderer Feature" to add a new image effect into your pipeline.

Here we've exposed a Material parameter we can assign to do the work of the image effect. It will get the rendered scene texture passed to it as its `_MainTex`, and whatever it outputs will be the result passed down the rest of the pipeline.

Now for the graph! For starters, here's the shading texture I'm using, a leftover from a shader workshop a few years back:

We'll start by creating a new unlit shader graph, and configure properties for...

* The `_MainTex` scene texture we want to stylize (it helps to take a screenshot of your game render and use this as the default texture, so you get a representative preview in the shader graph editor)
* The hatching swatch texture we want to use
* A "crossfade" variable we can use to blend between our stylized version and the original. This both allows us to control the intensity of the effect, and helps with debugging the graph, by letting us peek at the unmodified input when we need to.

Then we draw the rest of the owl:

Okay, let's break that down step by step. First we want to clamp the image into the 0-1 range (sorry HDR - we're gonna ignore you for simplicity in our first attempt), and dot it with the relative luminance constants to reduce it to greyscale, weighting the brighter green channel much more heavily than the dark blue channel.

You can also divide by this value to recover the scene's chromaticity, with the shading removed. We can use that to preserve the colour in our image later, so that we don't double-dip on shading by layering our hatching on top of an already-shaded image.

Next we need to compute the UVs to sample inside a single hatching swatch.

Because we're mapping this in screen space, it can start to look like something painted on the camera lens, since it doesn't move as content in the scene does. Adding a pseudo-random jitter into the UVs helps mask that, making it look more like the image is being redrawn at a framerate of your choosing. But you can also delete the top box if you want your hatching to stay fixed on the screen.

The "Fraction" node at the end handles wrapping the UVs into the 0-1 range for us. Since our swatch texture has bands of different shading side-by-side, we need to do that wrapping ourselves to keep from peeking into an adjacent swatch.

Here's where the magic happens:

We take our computed scene luminance in from the bottom-left, and multiply it by our number of shading ranges we have `(swatch count - 1)`. Taking the floor of this gives us the index of the swatch at the dark end of this range.

We add this to our screenspace UV, then divide the resulting horizontal value by our swatch count to get it into the 0-1 range of our texture lookups. Then we sample the dark swatch.

Adding `1 / swatch count` horizontally gets us the corresponding point in the next brighter swatch, and we sample that too.

Note I'm using the Texture 2D LOD node to say "we don't need mipmapping" - otherwise the jumps where we wrap-around inside a swatch look to the GPU like a texture being sampled from a long distance away, and it tries to mipmap them down to reduce aliasing, making line artifacts in our image.

Lastly, we subtract our floored luminance from the multiplied version, to get our fraction of the way between the dark and bright ends of the range. We use this as an interpolation weight to blend our two swatch samples.

We can multiply our sampled hatching with the chromaticity we calculated earlier to re-introduce the scene's colour, but with our new stylized shading.

And of course, lerp between the original input texture and our stylized result, using our cross-fade variable, so we can control the intensity of stylization.

Here's what this looks like in my example, using the default sample scene:

---
Tags: shaders, unity-shader-graph
---


title: Clamp joystick rotation in Unity

text:
# Question
Title: Clamp joystick rotation in Unity
I'm trying to create a mobile joystick using this free package from Unity. Here is the code for rotation which seems to be working fine. I just want to clamp the rotation to +90 or -90 degress. I have tried using the mathf.clamp function but the plane(player) completes a full rotation.

```
public Joystick joystick;
float rotateVertical;
float rotateHorizontal;

float minClamp = -90.0f;
float maxClamp = 90f;

void Update()
{
    rotateVertical = Mathf.Clamp(joystick.Vertical * 1f, minClamp, maxClamp);

    rotateHorizontal = Mathf.Clamp(joystick.Horizontal * -1f, minClamp, maxClamp);

    transform.Rotate(rotateVertical, 0, rotateHorizontal);
}

```

If I change the value of minClamp to 0, then the plane doesn't rotate on the negative x axis but is still able to complete a full rotation on the positive x axis. Can someone please help me?

# Answer
> 1 votes
It looks like what you're trying to clamp isn't the joystick input, it's the rotation of the object.

For that, you want to apply something a bit like this:

```
public float minClamp = -90.0f;
public float maxClamp = 90f;
public float sensitivity = 1f;

Quaternion _initialRoation;
float _pitch, yaw;

void Start() {
    _initialRotation = transform.rotation;
}

void Update() {
    _pitch = Mathf.Clamp(_pitch + joystick.Vertical * sensitivity, minClamp, maxClamp);

    _yaw = Mathf.Clamp(_yaw - joystick.Horizontal * sensitivity, minClamp, maxClamp);

    transform.rotation = _initialRotation * Quaternion.Euler(pitch, yaw, 0);
}

```

---
Tags: unity, joystick
---


# Question
Title: #pragma target 3.0 or 3.5? What is gained. What is lost for compatibility with older systems
I've just designed an image-based layering system shader. Multiple textures with Alphas overlay to create a fully dressed character, using 1 material.

# pragma target 3.0 is where I had started (suggested default in UnityProjects).

After creating so many transparent-overlay layers in my code, I got this:

Shader error in 'Custom/Test': Too many texture interpolators would be used for ForwardBase pass (12 out of max 10)

The fix seems to be to upgrade to **#pragma target 3.5**

My game is going to be a Steam-distributed game, PC only.

What do I lose by using #pragma target 3.5? Will only super-dvanced PCs be compatible? Or should a fairly good/average PC be able to run this?

I don't know the intricacies of this subject.

# Answer
This seems to be explained in the Unity documentation:

> * #pragma target 3.5 (or es3.0) OpenGL ES 3.0 capabilities (DX10 SM4.0 on D3D platforms, just without geometry shaders).
> * Not supported on DX11 9.x (WinPhone), OpenGL ES 2.0.
> * Supported on DX11+, OpenGL 3.2+, OpenGL ES 3+, Metal, Vulkan, PS4/XB1 consoles.
> * Native integer operations in shaders, texture arrays and so on.

Comparing this to the numbers from the Steam hardware survey for May 2020:

> OVERALL DISTRIBUTION OF CARDS...MAY
>
> * DirectX 12 `92.02%`
> * DirectX 11 `3.99%`
> * DirectX 10 `2.23%`
> * DirectX 9 Shader Model 2b and 3.0 `0.04%`
> * DirectX 9 Shader Model 2.0 `0.00%`
> * DirectX 8 GPUs and below `1.72%`

So it looks like you'd exclude less than 2% of the Steam audience by using `#pragma target 3.5`.
> 1 votes

---
Tags: unity, shaders
---


# Question
Title: How to author custom objects in a tile map?
I've been using Tiled for my game engine but for objects I have to use points on an object layer and give it a name and use that to create map items in-game. This is really inefficient as I don't want to have to copy paste every time I want to place down a ammo pack.

Is there a better workflow I can use to create custom objects and instantiate them?

Ideally I'd like to export to XML, but that's not a deal breaker.

# Answer
so as it turns out Tiled already lets you give tiles properties, just click the '+' in the tileset editor and you can add variables which can be accessed by a library such as tmxlite, this took me about 5 minutes to implement in my engine
> 1 votes

---
Tags: tiled, editors, map-editor, asset-workflow
---


title: Merge angle range

text:
# Question
Title: Merge angle range
I have `AngleRange` class with define range to angles to detect if a angle is inside the range.

```
public class AngleRange
{
    private readonly double _from;
    private readonly double _to;
    public AngleRange(double from, double to)
    {
        _from = DoubleUtils.NormalizeAngle(from); // 0 <= x < 360
        _to = DoubleUtils.NormalizeAngle(to);
    }

    public bool Inside(double target)
    {
        if (_from < _to)
            return _from <= target && target <= _to;
        return _from <= target || target <= _to;
    }
}

```

The angles used is 0 \<= x \< 360. For example,

```
var range1 = new AngleRange(0, 15);
range1.Inside(10); // True
var range2 = new AngleRange(15, 0);
range2.Inside(10); // False

```

Because `range2` is from 15 to 0 which means any angles, that 0 \< x \< 15 should return false.

My problem is to merge two `AngleRange` into one. For example, `AngleRange(0, 15)` merge `AngleRange(10, 13)` should return `AngleRange(0, 15)` because `AngleRange(0, 15)` includes `AngleRange(10, 13)`.

If `AngleRange(0, 15)` merge `AngleRange(10, 17)`should return `AngleRange(0, 17)`.

However, `AngleRange(15, 0)` and `AngleRange(10, 13)`should not able to merge because they do not intersect.

I am having trouble to check if two `AngleRange` is intersect, within, or not intersect with another. This is the method I am try to make.

```
public bool TryMerge(AngleRange range, out AngleRange range)
{
    // if not intersect
    // return false

    // if within
    // return true, out larger one

    // return true, out a new one with merged bound
}

```

**Edit**

For someone want to know the usage of this, I use this in my shadowcasting class. The merge method is needed to merge different shadow.

# Answer
> 1 votes
Your method name should probably be "AngleRangesIntersect" looking at its return type. Seems like your one little function is trying to do a bit too much. It's not merging the angle ranges but checking if there's an intersection between them. First let's get this logic a function of its own, then we can build a "MergeAngleRanges" one on top of that.

Something like this should do the trick for checking if they intersect:

```
private bool AngleRangesIntersect(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  if (FirstAngleRange._from > SecondAngleRange._from
      && FirstAngleRange._from < SecondAngleRange._to)
  {
     return true;
  }
  if (SecondAngleRange._from > FirstAngleRange._from
      && SecondAngleRange._from < FirstAngleRange._to)
  {
     return true;
  }
  if (FirstAngleRange._to > SecondAngleRange._from
      && FirstAngleRange._to < SecondAngleRange._to)
  {
     return true;
  }
  if (SecondAngleRange._to > FirstAngleRange._from
      && SecondAngleRange._to < FirstAngleRange._to)
  {
     return true;
  }

  return false;
}

```

Obviously this is a bit of a hot mess riddled with duplication so I'd probably extract these conditionals out into their own private functions:

```
private bool EitherAngleStartsBetweenOthersRange(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  if (FirstAngleRange._from > SecondAngleRange._from
      && FirstAngleRange._from < SecondAngleRange._to)
  {
     return true;
  }
  if (SecondAngleRange._from > FirstAngleRange._from
      && SecondAngleRange._from < FirstAngleRange._to)
  {
     return true;
  }

  return false;
}

private bool EitherAngleEndsBetweenOthersRange(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  if (FirstAngleRange._to > SecondAngleRange._from
      && FirstAngleRange._to < SecondAngleRange._to)
  {
     return true;
  }
  if (SecondAngleRange._to > FirstAngleRange._from
      && SecondAngleRange._to < FirstAngleRange._to)
  {
     return true;
  }

  return false;
}

```

Then we can pop the refactor in and enjoy a much nicer Check:

```
public bool AngleRangesIntersect(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  if (EitherAngleStartsBetweenOthersRange(FirstAngleRange, SecondAngleRange))
  {
    return true;
  }
  if (EitherAngleEndsBetweenOthersRange(FirstAngleRange, SecondAngleRange))
  {
    return true;
  }

  return false;
}

```

Now that we have that bit of the logic squared away we can mosey on to the merging of the angles. Now as far as I understand it what you're trying to do is:

*If the angles intersect, create one god angle with the **max upper and lower bound.***

for that we'd probably stick a couple of extra functions in to return the min and max for angles.

```
private double GetSmallestLowerBound(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  // Allow for cases like (355, 10) merging with (5, 350)
  if (FirstAngleRange._from < SecondAngleRange._from ||
      FirstAngleRange._from > SecondAngleRange._to)
  {
    return FirstAngleRange._from;
  }

  return SecondAngleRange._from;
}

private double GetLargestUpperBound(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  // Allow for cases like (20, 10) merging with (15, 25)
  if (FirstAngleRange._to > SecondAngleRange._to ||
      FirstAngleRange._to < SecondAngleRange._from)
  {
    return FirstAngleRange._to;
  }

  return SecondAngleRange._to;
}

```

Now that we have all the pieces we can put together our final merge method:

```
public AngleRange MergeAngleRanges(AngleRange FirstAngleRange, AngleRange SecondAngleRange)
{
  if (AngleRangesIntersect(FirstAngleRange, SecondAngleRange))
  {
    return new AngleRange(GetSmallestLowerBound(FirstAngleRange, SecondAngleRange),
                          GetLargestUpperBound(FirstAngleRange, SecondAngleRange)));
  }
  return new AngleRange(0.0f, 0.0f);
}

```

Any troubles give me a shout.

# Answer
> 0 votes
After some others help and Google, I come up with this solution (written in C#).

**AngleRange**

```
public class AngleRange
{
    private readonly double _from, _to;
    private readonly bool _full;

    public AngleRange (double from, double to)
    {
        _from = DoubleUtils.NormalizeAngle(from);
        _to = DoubleUtils.NormalizeAngle(to);
        _full = false;
    }

    public AngleRange (bool full)
    {
        _from = 0;
        _to = 0;
        _full = full;
    }

    public bool Inside(double target)
    {
        if (_full)
            return true;
        if (_from < _to)
            return _from.AboutLesserThanOrEqual(target) && target.AboutLesserThanOrEqual(_to);
        return _from.AboutLesserThanOrEqual(target) || target.AboutLesserThanOrEqual(_to);
    }

    public bool TryMerge(AngleRange newAngleRange, out AngleRange resultAngleRange)
    {
        if (newAngleRange._full)
        {
            resultAngleRange = newAngleRange;
            return true;
        }

        if (_full || Equals(newAngleRange))
        {
            resultAngleRange = this;
            return true;
        }

        var aStart = _from;
        var aEnd = aStart > _to ? _to + 360 : _to;
        var bStart = newAngleRange._from;
        var bEnd = bStart > newAngleRange._to
                   ? newAngleRange._to + 360 : newAngleRange._to;

        var diffA = (aEnd - aStart)/2;
        var diffB = (bEnd - bStart)/2;
        var avgA = (aStart + aEnd)/2;
        var avgB = (bStart + bEnd)/2;
        var cosDiffA = Math.Cos(diffA.ToRadians());
        var cosDiffB = Math.Cos(diffB.ToRadians());

        var resultFlag = MergeFlag.None;

        if (Math.Cos((avgA - bStart).ToRadians()).AboutGreaterThanOrEqual(cosDiffA))
            resultFlag |= MergeFlag.BStartInsideA;
        if (Math.Cos((avgA - bEnd).ToRadians()).AboutGreaterThanOrEqual(cosDiffA))
            resultFlag |= MergeFlag.BEndInsideA;
        if (Math.Cos((avgB - aStart).ToRadians()).AboutGreaterThanOrEqual(cosDiffB))
            resultFlag |= MergeFlag.AStartInsideB;
        if (Math.Cos((avgB - aEnd).ToRadians()).AboutGreaterThanOrEqual(cosDiffB))
            resultFlag |= MergeFlag.AEndInsideB;

        if (NotHasFlags(resultFlag, MergeFlag.BStartInsideA, MergeFlag.BEndInsideA,
            MergeFlag.AEndInsideB, MergeFlag.AStartInsideB))
        {
            resultAngleRange = null;
            return false;
        }

        if (HasFlags(resultFlag, MergeFlag.BStartInsideA, MergeFlag.BEndInsideA,
            MergeFlag.AEndInsideB, MergeFlag.AStartInsideB))
        {
            resultAngleRange = new Shadow(true);
            return true;
        }

        if (HasFlags(resultFlag, MergeFlag.BStartInsideA, MergeFlag.BEndInsideA))
        {
            resultAngleRange = this;
            return true;
        }

        if (HasFlags(resultFlag, MergeFlag.AEndInsideB, MergeFlag.AStartInsideB))
        {
            resultAngleRange = newAngleRange;
            return true;
        }

        if (HasFlags(resultFlag, MergeFlag.AEndInsideB, MergeFlag.BStartInsideA))
        {
            resultAngleRange = new Shadow(aStart, bEnd);
            return true;
        }

        if (!HasFlags(resultFlag, MergeFlag.AStartInsideB, MergeFlag.BEndInsideA))
        {
            resultAngleRange = new Shadow(bStart, aEnd);
            return true;
        }
        throw new InvalidOperationException("This should never happen.");
    }

    private static bool HasFlags(MergeFlag resultFlag, params MergeFlag[] flags)
    {
        return flags.All(flag => (resultFlag & flag) == flag);
    }

    private static bool NotHasFlags(MergeFlag resultFlag, params MergeFlag[] flags)
    {
        return flags.All(flag => (resultFlag & flag) != flag);
    }
}

```

**MergeFlag**

```
[Flags]
private enum MergeFlag : short
{
    None = 0,
    BStartInsideA = 1 << 0,
    BEndInsideA = 1 << 1,
    AStartInsideB = 1 << 2,
    AEndInsideB = 1 << 3
}

```

Using `AboutGreaterThanOrEqual()` and `AboutLesserThanOrEqual()` instead of `>=` and `<=` because of rounding error on edge cases. It is a method combine thin `AboutEqual()` from here and `>` or `<`.

`_full` represents AngleRange is a full circle. `ToRadians()` is a method that coverts degree into Radians.

# Answer
> 0 votes
Let me know if I missed something

```
public bool TryMerge(out AngleRange range)
{
    bool toInside = Inside(range.to);
    bool fromInside = Inside(range.from);

    // if not intersect
    // return false
    if (!toInside && !fromInside)
        return false;

    // if within
    // return true, out larger one
    if (toInside && fromInside)
    {
        //pick one
        range = new AngleRange(from, to);
        //range.to = to; //range.from = from;
        //range = this;
        return true;
    }

    //by default, should be here
    // return true, out a new one with merged bound
    range = new AngleRange(Math.Min(range.from, from),
                           Math.Max(range.to, to));
    return true;
}

```

# Answer
> 0 votes
Here is a much simpler and performant version which works fine also when start angle is higher then end angle (e.g. 350 - 10 degrees)

```
static bool GetMergedAngleRange(double start1, double end1,
  double start2, double end2,
  out double start, out double end)
{
  start1 = DoubleUtils.NormalizeAngle(start1);
  end1 = DoubleUtils.NormalizeAngle(end1);
  start2 = DoubleUtils.NormalizeAngle(start2);
  end2 = DoubleUtils.NormalizeAngle(end2);
  start = double.NaN;
  end = double.NaN;

  if (start1 > end1)
  {
    end1 += 360;
    start2 += 360;
    end2 += 360;
  }

  if (start2 > end2)
  {
    end2 += 360;
    start1 += 360;
    end1 += 360;
  }

  if (!(start1 < end2 && start2 < end1))
    return false;

  start = DoubleUtils.NormalizeAngle(Math.Min(start1, start2));
  end = DoubleUtils.NormalizeAngle(Math.Max(end1, end2));
  return true;
}

```

---
Tags: mathematics
---


# Question
Title: Is it useful to distinguish between two different kinds of events?
i have thought about this for a long time and i think i just going in circles. I need someone to tell me if im just simply overthinking it.

So, first of all im coming from a 'classical' ECS approach: You got entities that are basically just Ids, Components to these IDs in different colors (PosComponent, 2dGraphicComponent, etc.) and your systems working on those components. Im still working on an game engine, so none of these components are fix.

Now i have an event manager that accepts events. Currently these events are like MouseButtonClicked, KeyPressed, WindowResized etc. These are events, certain systems have to react to these events immediately and can't wait to be resolved in the next game loop. So the polling for these events is at the beginning of the loop. Since the event manager does not know, that system handles this event, every system needs to be called in order, until one system handles the event and gives a positiv feedback. So for example if you click on the gui, you don't want to shoot a bullet.

Then there are events, that always have some context attached to it. Like an event onCollision, where a sound should be played and the player takes damage. In this case this event would need to be handled by two different systems and in context of the collided object. Bumping spikes might actually kill you, while colliding with an enemy may just hurt you. And of course the sounds are different.
Additionally, you may have events that are delayed to trigger. Faraway sounds like gunshots only move with the speed of sound, so delay it in regards to the distance. Or Buffs and Debuffs that run out. So these events should have a connection to a component or entity (id) and some sort of *time to dispatch*.

These two event types seem so distinct that i can't even think of realizing both as one class, or at least not the all the assumptions i made.

Maybe this is a stupid question, but should i create two different event types and thus eventManager? In my internet searches i have not found anything about this problem, but maybe my Google Fu is a bit rusted.

# Answer
A common solution to free systems from having to process every single event is by using a subscription architecture. Individual systems can subscribe to specific types of events. The event dispatcher manages these subscriptions and dispatches events to only those systems which subscribed to them.

You can then further enhance the architecture by allowing conditional subscriptions. Like only receiving events for specific entities or only events which happen in a specific area. Just make sure that the event dispatcher is actually in a better position to filter events than the subscribers themselves and can make the decision for multiple subscribers at the same time. Otherwise there is not much gain from moving the logic for discarding events from the subscribers to the dispatcher.

Delayed actions like running out buffs is something I would not try to handle in the event system. There are just too many edge-cases which would require to cancel such an event prematurely. For example, what happens with the already scheduled buff end events when an entity is destroyed before its buffs run out? I would rather handle such timing problems in the systems themselves which would then create a "buff end" event when it actually happens.
> 2 votes

---
Tags: architecture, events, entity-component-system
---


# Question
Title: How to use the Vulkan graphics backend in the Stride game engine?
What do I have to do in order to run my Stride game on the Vulkan graphics platform?

The documentation section seems to be outdated, the drop-down doesn't exist anymore: https://doc.stride3d.net/latest/en/manual/platforms/index.html#set-the-graphics-platform

# Answer
Since Stride 4.0 you can add the `StrideGraphicsApi` property to the top-level executable project. For example, add this line in the first `PropertyGroup` of the .csproj file:

```
<StrideGraphicsApi>Vulkan</StrideGraphicsApi>

```

Valid values are:

```
Null
Direct3D11
Direct3D12
OpenGL
OpenGLES
Vulkan

```
> 0 votes

---
Tags: c#, vulkan, stride
---


# Question
Title: Which collider to use on "island" situation?
I have a 2d-top-down-unity game where the player is on an island. The shape of the island is random generated and he is not able to "escape" from the island.

So which Collider should I use for realizing this?

Is there some form of an "inverted" collider? Are colliders able to have a hole in them? Or should I create a polygon collider with a small gap (This could be quite difficult if the polygon bends the wrong way)?

# Answer
An EdgeCollider2D would handle this case well.

Much like a LineRenderer, you provide it a list of points to join into line segments, marking your collision boundary. It can be a closed shape, but it is not required to be closed.
> 3 votes

---
Tags: unity, 2d, collider
---


# Question
Title: Can a game world be made using a 3D editor?
I'm just wondering it it's possible to create and render a game world in a 3D modelling program, such as Blender, with landscapes and trees and such, and then import it into a game engine? Is that how open world games make their worlds, or do they use another method?

# Answer
> 2 votes
This is in fact how it used to be done in the past and still works in some Engines like Godot that lack a build in Terrain-Tool. It's totally possible to make a terrain in Blender and import it to your engine as a gigantic static mesh. But you don't want to include stuff like Trees in your terrain mesh. Those are better made a separate object. Especially for repeating objects like trees you want to use instanced drawing to not run into performance issues.

That being said, this approach has major drawbacks. You would need to re-import your terrain every time you make changes to it in your external software. When tweaking it you won't see any of the other game objects you placed into your engine editor. For larger maps you would also have to split it into parts, make sure they fit together seamlessly, create LODs etc. Depending of the complexity of your terrain this can get a huge problem. Especially for large open world games this is a 100% not the way to go.

Long story short: Yes it's technically possible, but not recommended unless your project is so small that it won't cause any issues. If your Engine has it's own Terrain-Tool i would heavily recommend you to just use it.

# Answer
> 1 votes
It can work for smaller and less detailed landscapes. But with larger and high-detail landscapes, you will run into performance problems. You will need LOD, occlusion culling and perhaps even dynamic loading and unloading of parts of the landscape. With most engines, none of that can work if the whole landscape is just one block of geometry.

Which is why many 3d engines have specialized systems for terrain rendering. These usually come with their own editors. The workflow is usually to sculpt the terrain in the engines terrain editor, design individual props like buildings or plants in a 3d modeling program and then place these props on the terrain using the editor.

---
Tags: 3d, game-design
---


# Question
Title: Problem With Enemy Bullets Attacking The Player Pygame
I am trying to make my enemy bullets attack the player but it only attack its x and y ***how could I make it curve instead of zigzagging*** VIDEO the bullets only attack the y axis and it wont curve or go to the player only attacks 2 positions

this goes on my main loop and appends projectiles

```
         for shootss in shootsright:

                if shootss.x < 500 and shootss.x > 0:

                    if enemyshoots1.x < playerman.x:

                        shootss.x +=  5
                    else:
                        shootss.x -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))
                if shootss.y < 500 and shootss.y >0:
                    if enemyshoots1.y < playerman.y:
                        shootss.y += 5
                    else:
                        shootss.y -= 5
                else:
                    shootsright.pop(shootsright.index(shootss))

            if len(shootsright) < 2:
                    shootsright.append(Bools(round(enemyshoots1.x+enemyshoots1.width-107),round(enemyshoots1.y + enemyshoots1.height-50),(0,0,0)))
                # projectile class for each of the bullets

```

my enemy bullets class

```
    # enemys bullets
    ksud = pygame.image.load("heart.png")
    class Bools(object):
       def __init__(self, x, y,color):
           self.x = x
           self.y = y
           self.ksud = pygame.image.load("heart.png")
           self.hitbox  = self.ksud.get_rect()
           self.rect  = self.ksud.get_rect()
           self.rect.topleft = (self.x,self.y)
           self.speed = 10
           self.color = color
           self.hitbox = (self.x + 57, self.y + 33, 29, 52) # NEW
       def draw(self, window):
            self.rect.topleft = (self.x,self.y)
            player_rect = self.ksud.get_rect(center = self.rect.center)
            player_rect.centerx += 0 # 10 is just an example
            player_rect.centery += 0 # 15 is just an example
            window.blit(self.ksud, player_rect)
            self.hitbox = (self.x + 97, self.y + 33, 10, 10) # NEW
            window.blit(self.ksud,self.rect)

```

I have something similar for the player where ever I click it appends bullets how could I change it to append bullets at the player without the click?

```
                # this is for the bullets
                    if len(bullets) < 2:
                        shootsound.play()

                        start_x, start_y = playerman.x+playerman.width//2, playerman.y + playerman.height-54
                        mouse_x, mouse_y = event.pos

                        dir_x, dir_y = mouse_x - start_x, mouse_y - start_y
                        distance = math.sqrt(dir_x**2 + dir_y**2)
                        if distance > 0:
                            new_bullet = projectile(start_x, start_y, dir_x/distance, dir_y/distance, (0,0,0))
                            bullets.append(new_bullet)
        # this is displaying the bullets for the player
            for bullet in bullets[:]:
                bullet.move()
                if bullet.x < 0 or bullet.x > 900 or bullet.y < 0 or bullet.y > 900:
                    bullets.pop(bullets.index(bullet))

```

# Answer
Your problem is here:

```
            if enemyshoots1.x < playerman.x:
                shootss.x +=  5
            else:
                shootss.x -= 5

            if enemyshoots1.y < playerman.y:
                shootss.y += 5
            else:
                shootss.y -= 5

```

If you want the bullet to move straight towards the player, you need to employ some trigonometry. Unfortunately, I have never used PyGame, and its been quite some time since I used python, so the best I can give you is some C#-looking psuedocode. You will want something like this:

```
//define bullet speed
float bulletSpeed = 5.0f;

//the number of degrees or radians between your bullet spawn and player
//this is possible using the screen or world coordinates of your
//sprites and some built in functions to calculate the angle
float angle = angle from player.x / player.y and bulletSpawn.x/bulletSpawn.y;

//again, use built in functions to calculate these values:
float xMagnitude = cosine of angle;
float yMagnitude = sine of angle;

//update the bullet
shootss.x += xMagnitude * bulletSpeed;
shootss.y += yMagnitude * bulletSpeed;

```

Of course, it would be much better to cache the x and y magnitudes as a member variable in the bullet instance so that you aren't calculating these values for every bullet every frame.

EDIT:

Try something like this.

```
# enemys bullets
ksud = pygame.image.load("heart.png")
class Bools(object):
   def __init__(self, x, y,color, xspeed, yspeed):
       self.x = x
       self.y = y
       self.xspeed = xspeed
       self.yspeed = yspeed
       self.ksud = pygame.image.load("heart.png")
       self.hitbox  = self.ksud.get_rect()
       self.rect  = self.ksud.get_rect()
       self.rect.topleft = (self.x,self.y)
       self.speed = 10
       self.color = color
       self.hitbox = (self.x + 57, self.y + 33, 29, 52) # NEW
   def draw(self, window):
        self.rect.topleft = (self.x,self.y)
        player_rect = self.ksud.get_rect(center = self.rect.center)
        player_rect.centerx += 0 # 10 is just an example
        player_rect.centery += 0 # 15 is just an example
        window.blit(self.ksud, player_rect)
        self.hitbox = (self.x + 97, self.y + 33, 10, 10) # NEW
        window.blit(self.ksud,self.rect)

```

and

    for shootss in shootsright:
            shootss.x += shootss.xspeed
            shootss.y += shootss.yspeed
            if shootss.x > 500 or shootss.x < 0 or shootss.y > 500 or shootss.y < 0:
                shootsright.pop(shootsright.index(shootss))

        if len(shootsright) < 2:
            start_x = round(enemyshoots1.x+enemyshoots1.width-107
            start_y = round(enemyshoots1.y + enemyshoots1.height-50)
            target_x = playerman.x+playerman.width//2
            target_y = playerman.y+playerman.width//2
                    dir_x, dir_y = target_x - start_x, target_y - start_y
                    distance = math.sqrt(dir_x**2 + dir_y**2)
                    if distance > 0:
                        shootsright.append(Bools(start_x,start_y,(0,0,0),dir_x, dir_y))```

EDIT:

The last part of code makes the bullets fly to fast. A solution for this problem was found here
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Management of objects as targets of other objects
I have started my first game three years ago and learned a lot during that process. Now I would like to rewrite it to incorporate my "lessons learned" or try out new ideas.

My game consists of space ships that can target other space ships either for combating, trading or communicating. When they have no current target, they look for other ships in their area, lock them as target (by keeping a pointer to them as member variable) and do some stuff. After a ship is destroyed, its pointer used by other ships as a target becomes invalid. To avoid any dangling pointers and crashes, I add the *to be destroyed* `Ship`'s id to a cleaning list. During the next `World`'s update, I go through all of these *to be destroyed* ids and remove them as potential targets. See this pseudo code to demonstrate this:

```
class Ship
{
public:
    Ship();
    Ship::destroy(){
        // set to be destroyed flag
        _world.pointersToDelete(_id);
    }

private:
    void        destroy();

    int         _id;
    Ship*       _target;
    World*      _world;
    bool        _to_be_destroyed;

};

// in World::update
World::update()
{
    for (auto ship: all_ships)
    {
        for (auto id_to_delete: ids_to_delete)
        {
            if(ship._target != nullptr && ship._target->_id == id_to_delete)
            {
                ship._target = nullptr;
            }
        }
    }

    // now trigger the actual final destruction of the ships
    // ...
}

```

**Question:** Is this a good design in general? I ran into some problems when I used it in practice:

There are more objects that communicate, combat and trade with ships like Space Stations, Planets, etc.. I would need to go through all of them every update loop to check whether they have no dangling pointers. I am concerned about the performance since my game allows space battles of thousands of ships at the same time.

I thought about using an id approach instead: the `_target` variable is not a pointer but an id that I can look up in an `unordered_map` of `Ship` objects. If the id is not found anymore, the target is not valid any longer. But this could lead to performance issues as well if every object has to check this during every update multiple times.

# Answer
I believe an option available to you is to use `std` smart pointers, more specifically the `std::shared_ptr` and `std::weak_ptr`.

Typically, those pointers represent ownership. They also offer a ref-counting mechanism, and I think it's *this* feature that you're after.

`std::shared_ptr`s hold a reference to a dynamically allocated object, a count of "hard" references (i.e. how many `shared_ptr`s point to this object) and a count of "weak" references (i.e. how many `weak_ptr`s point to this object). When the ref count for "hard" references reaches 0, the dynamically allocated object is destroyed. When the "weak" count reaches 0, the ref-counting object is deleted.

Although you don't seek to share the ownership, you could use the pattern that "shared pointers represent ownership", and still have only one shared pointer over your object, and use the `std::weak_ptr` to represent "links" to those object.

`std::weak_ptr`s don't keep objects alive, only `std::shared_ptr`s do.

So you keep `std::shared_ptr<Ship>` in your `World::all_ships` collection (e.g. `std::vector<std::shared_ptr<Ship>>`), but your `Ship`s keep references to `std::weak_ptr<Ship> _target;`.

Once you need access to it, it could be a simple matter checking if the \_target is still there and creating a temporary "hard" reference to it, until you need it:

```
Ship::attack()
{
  if ( !_target.expired() )
  {
    if ( auto lockedTarget = _target.lock() )
    {
       lockedTarget->_health -= 42;
    }
  }
}

```

Later, if you decide that the `Ship` pointed by a `Ship::_target` needs to be destroyed, then you just delete the `std::shared_ptr<Ship>` that points to it; whenever you'll try to reference to it through the weak\_ptr like shown above, it will not cause any issue, and the ship's health will not be decreased, as it will not be able to lock the pointer.

This is *one* option, and I believe it's the easiest and fastest to implement in the situation I think you're in. Know that locking often `weak_ptr`s into `shared_ptr`s *could* cause slowdowns as this has been developed with "atomicity" (multi-threading) in mind. I would still suggest to try it, and then profile it. If it works for your situation, then you're good to go and work on the next top item on your long list.

If this doesn't work, then, as it's been suggested in the comments, you could look into a component based architecture (e.g. Entity-Component-System), but that would require you to change *a lot* of things in your game.
> 4 votes

---
Tags: c++, architecture, gameobject
---


title: How to do this once in Update?

text:
# Question
Title: How to do this once in Update?
I want to add 1 to directions every time the shift key is pressed. Since I need to check the key press, I have to do it in `Update`, but in Update this code is executed multiple times and the directions goes all the way up to 4 before going back to 1.

How do I make it so that every time the **shift key** is pressed, directions is added by 1 and only 1? Thanks in advance. :)

```
private int directions = 1;

var keyboard = Keyboard.current;

if (keyboard.shiftKey.isPressed)
        {
            directions++;

            if (directions == 5)
            {
                directions = 1;
            }

        }

```

# Answer
Use `wasPressedThisframe` instead of `isPressed`. :)
> 3 votes

---
Tags: unity
---


title: AI - Tactics for out of range enemies

text:
# Question
Title: AI - Tactics for out of range enemies
I'm working on a Fire Emblem style tactical engine, and looking into the AI.

I have it working so enemies will find the best target within their movement/attack range, but what about when no units are within range- for example at the start of the map when they're far away. Who do they decide to move towards?

Does it just pick out the weakest from the player units? Does it go for the nearest?

# Answer
I have seen a lot of turn-based tactics games where enemy units simply stay idle unless there is an enemy in range. This isn't necessarily the strongest solution and might allow a clever player to cheese if they can somehow find a way to damage enemies while still ending the turn outside of their movement range (Some of the *Disgaea* games allowed that exploit under some circumstances). But it can still be a "good enough" solution for many games. It also allows you to create longer combat scenarios where the player army slowly progresses through a larger but sparsely formatted enemy army step-by-step. If the AI is too aggressive at moving in on the player instead of waiting for them to arrive, then this becomes very difficult to design.

But let's say you do want to go the extra mile and have an AI which behaves more aggressively.

Just walking in the direction of the closest enemy unit is a valid option. I would prototype this, playtest a bit and see how it works out. But if you want the AI to be extra smart, you could use the rating function you are already using to determine targets, but apply it to all enemy units and add the distance as another factor. So the AI will balance target distance with target desirability when deciding which target to close in on. The ideal balance factor is a matter of preference. A "perfect" AI would measure distance in turns, not in tiles. But measuring by tiles might make the AI appear more human. It would replicate the human bias for attacking enemies which look closer even though from a purely game-mechanical view all units which can be reached within one turn are technically the same distance.
> 0 votes

---
Tags: ai
---


# Question
Title: How do I play an audio clip repeatedly, controlled by time?
I have a gun firing sound audio clip and I want this to be played repeatedly while the mouse left button is pressed, like a machine gun where there is automatic firing.

If I do something like:

```
void Update()
    {
        if (gunScript.gotGun)
        {
            var mouse = Mouse.current;
            var gamepad = Gamepad.current;

            if (mouse != null)
            {
                if (mouse.leftButton.isPressed)
                {
                    gunFireSound.Play();
                }
            }
        }

    }

```

It plays extremely rapidly as that's how the code gets executed very fast. How do I add a small delay or is there a better way to achieve this?

I also thought of an alternative but it doesn't play it fast enough. (the alternative was an if statement to check if it is finished playing, and play it again)

Thanks in advance. :)

# Answer
You can manage this using a coroutine. For example:

```
private IEnumerator GunShotSound_Coroutine()
{
    while(mouse.leftButton.isPressed)
    {
        gunFireSound.Play();
        yield return new WaitForSeconds(1.0f);
    }
}

```

In the update function, you controlled if the leftbutton was pressed this frame and you start the coroutine.

```
if(Input.GetKeyDown(mouse.leftButton))
{
    StartCoroutine("GunShotSound_Coroutine");
}

```

I did not test this code but the idea is here :)
> 1 votes

# Answer
The simplest thing to do is to check whether the audio source is still playing the previous sound, and play a new one only if it's done:

```
if(!gunFireSound.isPlaying)
    gunFireSound.Play();

```

But that might make your shots sound too far apart. So you might want to allow your new shot to interrupt the old one after a specified duration.

```
if(!gunFireSound.isPlaying || gunFireSound.timeSamples > gunFireInterrupt)
    gunFireSound.Play();

```

Here `timeSamples` is a high-precision count of the individual audio samples played so far.

You can also use PlayScheduled to queue-up the next iteration of the shot at a fixed interval from the previous one, to make the rhythm of shots more uniform despite variances in frame timing.

But the best solution is probably to have a looping machine gun sound that you can start playing on press, and transition into a tail-off sound on release. This will give you the best control over the sound and rhythm of the shots, and avoid artifacts from interrupting a sound in progress.
> 2 votes

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


# Question
Title: Having Trouble holding PlayerPrefs after game restart
I am trying to create a highscore value that is stored in playerprefs, and only updates when a higher score is achieved. I got playerprefs viewer on the asset store, and can see that it is holding a value, but it seems that it blows through the if statement that checks to see if the new value is a highscore. This means that no matter what score I get, it always stores it as a highscore.

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

public class Score : MonoBehaviour
{
    public Transform Player;

    public Text scoreText, Highscoretext;

    public GameObject Postgame, Ingame;

    private bool stopScore = false;

    void Update()
    {
        if (stopScore == false)
        {
            //Keeps track of and displays current score
            float floatscore = Player.position.x;
            int intscore = (int)floatscore / 10;
            if (FollowPlayer.gameOver == false)
            {
                scoreText.text = intscore.ToString();
            }

            if (FollowPlayer.gameOver == true)   // Checks wheather the game has ended (from a different script)
            {
                stopScore = true;   // Stops running the score function

                if (intscore > (PlayerPrefs.GetInt("HighScore")));   // Checks to see if the score of the current game is a new Highscore
                {
                    PlayerPrefs.SetInt("HighScore", intscore);   // Sets new Highscore

                    EndScreen();   // Function to load the endscreen
                }
            }
        }
    }
    public void EndScreen()
    {

        Highscoretext.text = "Highscore: " + PlayerPrefs.GetInt("HighScore").ToString();   // Supposed to set the endscreen Highscore value to the new Highscore value

        // Different canvas overlays
        Postgame.gameObject.SetActive(true);
        Ingame.gameObject.SetActive(false);
    }
}

```

I tried using Debug.Log to debug this, and found that even if `intscore` is smaller than `PlayerPrefs.GetInt("HighScore"))`, it will still run the code that sets a new highscore. Anyone have any idea of how to fix this?

# Answer
You need to remove the semicolon from this line:

```
if (intscore > (PlayerPrefs.GetInt("HighScore")));

```

The semicolon in that position ends the if/then block, making it essentially an if without a then. The following block where you assign to PlayerPref then gets run regardless of the if, since it is just a code block with superfluous braces, but completely unrelated to the if syntactically.
> 2 votes

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


# Question
Title: How to stop movement from moving multiple spaces when a directional key is pressed
I am making a 15 piece puzzle game and having difficulty making my sprite move one tile at a time, when i initially press the left key the sprite moves once, but after that the sprite moves multiple tiles after i press the keys again, instead of moving one tile like it should. Eventually this also messes with the sprites and some of them disappear. The code that i use to determine movement is:

```
if (positionx16 - positionx1 == 200 && positiony16 == positiony1)
{
    canswapleft1 = true;
}

if (oldState.IsKeyUp(Keys.Left) && newState.IsKeyDown(Keys.Left))
{
    if (positionx16 > 0 && canswapleft1 == true)
    {
        positionx16 += -widthoftile;
        positionx1 += widthoftile;
        canswapleft1 = false;
    }
}

```

The positionx16 is the X position of the player controlled tile, and the positionx1 referes to the X position of the 1st tile, this was repeated for each tile.

# Answer
> -1 votes
if what you want is going somewhere once per key press, try this:

```
if (positionx16 - positionx1 == 200 && positiony16 == positiony1)
{
    canswapleft1 = true;
}

if (oldState.IsKeyUp(Keys.Left) && newState.IsKeyDown(Keys.Left))
{
    if (positionx16 > 0 && canswapleft1 == true)
    {
        positionx16 -= widthoftile; // use -= instead of += -x
        positionx1 += widthoftile;
        canswapleft1 = false;
        while(newState.IsKeyDown(Keys.Left))
        { // do Nothing
          // Just wait until release
          // but note that you wont be able to do anything else, even updating other
          // stuff, so the player really needs to release the key.
        }
    }
}

```

this might not be efficient and can be not suitable for your game.

also i Don't see - on what you shared - that your oldState is set, do you have such a thing in your final code?

```
oldState = newState; // for example

```

---
Tags: xna
---


# Question
Title: Best way to make a Side Panel UI with Libgdx?
Take this image for example, the game is called Realm of the mad god, and it has this side panel filling the whole screen height with the player info.

To reproduce it, Is there any way to make the game "view" smaller so I can fit the side panel to its right without literally overlaying the game, PROBABLY like this game did, or is the only way out to overlay the game?

(Tibia might also be an example of a game smaller then its UI)

# Answer
"This looks like a job for a viewport. It looks like libgdx's version has a "right gutter width" property that would be useful here" - DMGregory found it!
> 1 votes

---
Tags: java, libgdx, gui, hud
---


# Question
Title: Why doesn't this movement script work, while the other one does?
Im trying to get a rigidbody2D to move around and got it working with this script:

```
public class RubyController : MonoBehaviour
{
public Rigidbody2D rigidbody2d;
public float speed = 5.0f;
Vector2 movement;

void Start()
{
    rigidbody2d = GetComponent<Rigidbody2D>();
}

void Update()
{
    movement.x = Input.GetAxis("Horizontal");
    movement.y = Input.GetAxis("Vertical");
}

private void FixedUpdate()
{
    rigidbody2d.MovePosition(rigidbody2d.position + movement * speed * Time.deltaTime);
}

```

but not with this, and I can't understand why:

```
public class RubyController : MonoBehaviour
{
public Rigidbody2D rb2d;
float horizontal;
float vertical;
public float speed = 5f;

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

private void Update()
{
    horizontal = Input.GetAxis("Horizontal");
    vertical = Input.GetAxis("Vertical");
}

private void FixedUpdate()
{
    Vector2 position = this.rb2d.position;
    position.x = position.x * speed * horizontal * Time.deltaTime;
    position.y = position.y * speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}
}

```

# Answer
It looks like you want:

```
private void FixedUpdate()
{
    Vector2 position = this.rb2d.position;
    position.x = position.x + speed * horizontal * Time.deltaTime;
    position.y = position.y + speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}

```

Note that the operator before `speed` is a `+` for addition (we want to *add* this frame's movement to the current position), not a `*` for multiplication (multiplying our position by this frame's movement... doesn't make much sense geometrically)

Or, a little less typing:

```
private void FixedUpdate()
{
    Vector2 position = rb2d.position;
    position.x += speed * horizontal * Time.deltaTime;
    position.y += speed * vertical * Time.deltaTime;

    rb2d.MovePosition(position);
}

```
> 1 votes

---
Tags: unity, c#, movement, rigidbody
---


# Question
Title: Apply Secondary Normal Map to Standard Shader by Script
I have a material with an existing normal map. I added a secondary normal map to represent damage via script. I assign to the appropriate texture property `_DetailNormalMap`, assign the required keywords, `_DETAIL_MULX2 _NORMALMAP`, and set a scale via `_DetailNormalMapScale`.

I have ensured there is a material in the resources folder with the same settings, to ensure that the variant is available in builds, though this shouldn't be an issue in editor.

However, it does not show up, at least not initially:

If I do darn near anything with it in the editor, even alt+tabbing, will cause the secondary normal map to show up:

I recall back in the day keywords were the issue, but I clearly have done that. I recall this working in the past. I am still using Unity 2018.4.6f1, so I would be surprised if there are any major changes.

Thanks for your assistance.

# Answer
Turns out the issue was that a constant that represented the keyword was updated to have two keywords instead of just one. In effect, we were doing:

```
material.EnableKeyword("_DETAIL_MULX2 _NORMALMAP");

```

Instead of:

```
material.EnableKeyword("_NORMALMAP");
material.EnableKeyword("_DETAIL_MULX2");

```

Both `_NORMALMAP` and `_DETAIL_MULX2` are required for the secondary normal map to work, and they each must have their own call from `EnableKeyword`.
> 1 votes

---
Tags: unity, shaders, rendering, materials, normal-mapping
---


# Question
Title: Ocean visible through the island's lake in Unity3D?
I'm working on a puzzle game featuring islands: there is a **plane with a water shader**, and **objects colliding with that plane**.

Now I'd like to make **lakes** on the islands, with **different (higher) water levels** than the ocean's.

The problem is that if I put a water plane in a "hole", I can see the ocean below at best, or even worse, the upper water surface just glitches out and disappear.

One option is that I **move the lake's basin higher** than the ocean's see level. This works, but I it doesn't look so good, because the lake becomes too shallow.

Another option is that I **cut holes in the ocean's plane**, but that seems a bit overengineered, isn't it?

**Is there a better solution?**

Also having a water plane for every "lake tile" causes some problems:

but I want to have dynamic lakes, so having a 2x2 water plane for a 2x2 group of lake tiles isn't a walkable path.

# Answer
Based on this answer: Fade in rendering mode doesn't work as intended

I've put a quad just above the ocean's gameobject in my lakes, with a material with this shader:

```
Shader "Custom/DepthReserve"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType" = "Opaque" "Queue"="AlphaTest+1" }
        LOD 100

        Blend Zero One

        Pass
        {

        }
    }
}

```

So this quad "reserves" the depth, not letting the ocean mesh to be shown.
> 1 votes

---
Tags: unity, shaders, graphics, water
---


# Question
Title: In my browser game's website description, can I use a title of another game?
For instance, if I think my game is a cross between Age of Empires and Minesweeper, can I have written on the description of my website "A browser-based hybrid of Age of Empires and Minesweeper" ?

Thanks!

# Answer
> 4 votes
First up: I am not a lawyer, and the following is not legal advice. For legal advice, you should always consult a lawyer.

Drawing from Examples & Explanations for Intellectual Property by Stephen M. McJohn, there are multiple actions that might be considered infringement of a trademark, including:

> **Implied Endorsement**
>
> ...If a consumer sees a mark used in marketing goods or services, she may consider whether the mark owner has authorized the use. If she assumes that every legal use of a mark requires permission of the mark owner, she would likely assume that almost any use of the mark was endorsed by the mark owner.

> **Initial Interest Confusion**
>
> The "initial interest confusion" doctrine finds liability when defendent's use of the mark may attract the attention of potential consumers looking for the products associated with the mark, even though the confusion is dispelled before a sale is made.

Based on this, it's conceivable to me that the IP holder for one of the games you reference could try to sue you for using their trademark without permission, claiming that you are implying an endorsement or exploiting initial interest confusion to promote your game off the value of their IP.

Whether such a lawsuit would actually succeed in court, I cannot say. But it doesn't have to succeed in order to bankrupt you as you try to defend against it.

You could however reference the genres of related games (like "RTS" or "sweeper puzzle"), to attract players searching for similar keywords, without drawing the ire of a specific company's legal department.

---
Tags: legal, trademark
---


# Question
Title: Best way to handle tick-based resource generation in an online multiplayer strategy game
I'm building an online multiplayer strategy game. The game has no offline mode and requires syncing up to a server. Part of this game is constructing buildings which will generate resources each second. These resources would be generated whether the player is online or offline.

If this was a purely offline game, this would be easy: get the delta between when the app was closed and when it was opened again and multiply by resources per second and just fast forward everything.

Since it's an online game, and other players can be affected by the resources an offline user has, these calculations have to occur on the backend.

My question is: if I have 10,000 players, each with 20 buildings generating resources on a per second basis, how on earth should I handle 200,000 things all at once and syncing to a database?

# Answer
> 1 votes
Recalculate (fast-forward) resource amount on each use.

* On server, recalculate after db fetch and keep it cached for duration of current request. Do not store into db unless it's modified explicitly, e.g. withdrawn or deposited. Anything that affects growth rate must trigger update too.
* On client, do it every time value is used (mostly for rendering, I presume), or do it periodically with e.g. 1 second interval. Carefully synchronize time between client and server to minimize desync issues.

(Throwing in some code because why not.)

```
class PassivelyGeneratedResource
{
    public readonly DateTime SnapshotTime;
    public readonly int SnapshotValue;
    public readonly double GrowthRatePerSecond;

    int? _cachedValue;
    public int CurrentValue => _cachedValue ?? (_cachedValue = Recalculate());

    void Recalculate() {...}
}

```

---
Tags: unity, game-design
---


# Question
Title: Unity AudioMixer sets AudioSources to 0 regardless of decibel value
My code for the decibel and volume/linear conversion is good already. I just can't figure out why my AudioMixer keeps on setting my AudioSources to 0. I've double checked to see if my decibel value on my AudioMixer is updating. It updates accordingly. But, my AudioSources remain to have a volume of 0 regardless of any update or not.

Any ideas on what could be the problem?

# Answer
> 1 votes
update. when I tried reproducing the problem on a fresh project, it works. Just then, I realized that one of my old scripts updates the volume of the `AudioSource` before the other script can validly update the volume.

---
Tags: unity, audio
---


# Question
Title: How do I get an unique hardware id with gdscript?
Using Godot Engine, I'm trying to implement digital rights management (DRM) using an uuid, and I want to get the user's MAC address. Is there an easy way to do this with gdscript?

On Linux, I could call OS.execute to run "ip link show" and parse out mac addresses from the output. However, I would rather not maintain platform specific versions. I also hope to avoid having to compile in native code.

# Answer
> 2 votes
As described in the doc, the function `OS.get_unique_id()` seems to do what I need, which is getting a constant string that is unique to the device. I don't know for certain that this uses the MAC address, but it satisfies the intent of my question.

```
var _user_id = OS.get_unique_id()

if can_user_reticulate_the_spline(_user_id):
    # ...

```

---
Tags: networking, godot
---


# Question
Title: How to show game screen in one viewport and minimap in another, with different sprites on each?
All tutorials I've found about this link to the splitscreen demo, but it is made under Godot version 2 and does not work in version 3.

I want to render the world in the main viewport and its simplified view on the minimap in another viewport using two different cameras.

In the main viewport the main `AnimatedSprite` node of objects should be rendered, and on the minimap there are only additional `Sprite` nodes of objects showing their schematic view.

I tried to do:

```
Node2D
-ViewportContainer
--ViewportMain
--- Camera2D
--- World
----Player
-----AnimatedSprite # for main viewport
-----Sprite # for minimap
----OtherObjects
-----AnimatedSprite # for main viewport
-----Sprite # for minimap
-ViewportContainer
--ViewportMinimap
--- Camera2D

```

In code I assign the main viewport's world to the minimap's viewport:

```
$ ViewportMinimap.world = $ ViewportMain.world

```

For the main `AnimatedSprite` I set Light Layer #1, for the sketchy `Sprite` I set Light Layer #2.

And it does not work.

Firstly, nothing is displayed on the minimap. I don’t understand how to make it work. How to tell the minimap's viewport to use the world from the main viewport?

Secondly, I can’t find anywhere how to set on the camera which Light Layer it has to display (in the three-dimensional Camera there is a Cull Layer parameter, but I don’t see it here).

Will this approach hit performance?

How to correctly implement a minimap without needing to modify it when you add new objects to the game?

How to correctly replace scenes when player moves from one to another if it's a child of the Viewport?

# Answer
> 1 votes
I solved it. Here is project with working solution: https://gamedev.ru/files/?id=146737

I should to use world\_2d instead of world variable.

```
$ViewportMinimap.world_2d = $ViewportMain.world_2d

```

---
Tags: 2d, camera, godot, viewport, minimap
---