# Question
Title: DirectX11 - Texturing Terrain Mesh with Shared Vertices
I'm trying to create and texture a terrain mesh in DirectX11. I've managed to create the mesh itself, but I don't know how I should do the texturing. Let me start by explaining what I'm doing so far:

I have a vertex structure that looks like this:

```
struct Vertex
{
    XMFLOAT3 position;
    XMFLOAT4 color;
};

```

Then I create all the vertices for the terrain mesh:

```
for (int z = 0, index = 0; z < terrainHeight; ++z)
{
    for (int x = 0; x < terrainWidth; ++x, ++index)
    {
        vertices[index].position = XMFLOAT3(x, 0.0f, z);
        vertices[index].color = XMFLOAT3(1.0f, 1.0f, 1.0f, 1.0f);
    }
}

```

Then I create all the triangles for the terrain mesh with indices:

```
for (int z = 0, index = 0; z < terrainHeight - 1; ++z)
{
    for (int x = 0; x < terrainWidth - 1; ++x)
    {
        indices[index++] = (z    ) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x + 1);

        indices[index++] = (z    ) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x + 1);
        indices[index++] = (z    ) * terrainWidth + (x + 1);
    }
}

```

With 256x256 vertices I get this result (rendering in wireframe):

I'd now like to change the color to a texture, so I change the Vertex structure to this:

```
struct Vertex
{
    XMFLOAT3 position;
    XMFLOAT2 texture; // Changed the color to a texture coordinate.
};

```

And this is where I get stuck. Since each vertex now have a texture coordinate (U, V) I'd like to set it up like this:

But each vertex can only hold one texture coordinate. As you can see, the 2 vertices between square A and B needs 2 different texture coordinates each in order to map it correctly. If I'd loop through each pair of triangles, then when I reach square B I'll overwrite the texture coordinates that was correct for square A.

So therefore I have some questions:

1. Am I doing this in the "right" way? How does modern games do it? Do they texture each square or the entire mesh?
2. If I'd like to texture each square, how can I solve this problem?

# Answer
The best way I have found to do terrain texturing is using color maps to splat textures, with this method the only vertex info you need is a float3 for the vertex positon as there is no need to pass in texture cords.

First up you draw around your terrain using each color channel for a different texture.

Color map: Red = beach Green = under water Blue = grass

Then in your pixel shader you use the world space vertex position like this to build your texture cords and sampel your 3 terrain textures to build a nice blended terrain.

```
Texture2D ColorMap;
Texture2D DiffuseMap0; //Terrain Texture
Texture2D DiffuseMap1; //Terrain Texture
Texture2D DiffuseMap2; //Terrain Texture

float4 Texcords;

//Color map cords, 4096 *8 = terrain size, you will have to play with this. You sample your Colormap with this

Texcords.xy = input.WorldPos.xz / (4096 *8);
Texcords.xy += 0.5;

//Terrain texture cords, TextureScale = 1024 you will have to play with this value. You sample your terrain textures with this.

Texcords.zw = dout.PosW.xz / TextureScale;

//ColorMap
float4 Layer1 = ColorMap.Sample(pointsamp, Texcords.xy); //pointsamp = point sampling.

float total = Layer1.r + Layer1.g + Layer1.b;
Layer1.rgb /= total;

//Terrain Textures
float4 TerrainColor;
TerrainColor+= DiffuseMap0.Sample(samANISOTROPICWrap, Texcords.zw) * Layer1.r;//ANISOTROPICWrap = ANISOTROPIC Wrap sampling
TerrainColor+= DiffuseMap1.Sample(samANISOTROPICWrap, Texcords.zw) * Layer1.g;//ANISOTROPICWrap = ANISOTROPIC Wrap sampling
TerrainColor+= DiffuseMap2.Sample(samANISOTROPICWrap, Texcords.zw) * Layer1.b;//ANISOTROPICWrap = ANISOTROPIC Wrap sampling

```

What you end up with is under water texture where the green is, sand where the red is and grass where blue is.

You can also get some really cool blending by using a custom color value rather than green=(0,255,0,255) you can go things like green=(0,200,0,127) and that way you would let a bit more of the blue or red come into play when the textures get sampled on the gpu.

I use two color maps, one for low ground and one for mountains, in my color map the black spots will be filled in with another color map but just for the slops.

You can also look into tri planar mapping so you can avoid color maps.
> 2 votes

# Answer
If you want each quad to be a full uv range of \[0..1\[, then you do not need a texture coordinate stream in your vertex at all. Instead, in your shader

```
float2 tileDimensions; // number of quads in each direction
float2 terrainDimensions; // in object space
float2 texcoordFromPosition( float3 position ) {
  return frac( position.xy * tileDimensions / terrainDimensions;
}

```

By design, the input assembly works with full tuples. The only way to have on one point span over 2 triangles a texcoord at 0 AND 1 on each side is to split the vertex into 2 different ones.

You should note that the frac may introduce issues with the derivatives and mip mapping, you should just use the same function as above without the frac and set the sampler state with wrapping address mode.
> 0 votes

# Answer
With this color variable you allotted you can just change the color of the vertex.But when it comes to texture you have to create an image from the texture coordinates you have and then map this image to the corresponding terrain.Then you will get to see the textured terrain.I have done this in using OpengL so I cant give you code.
> 0 votes

---
Tags: textures, directx11, terrain-rendering, vertex-buffer, index-buffer
---


# Question
Title: Why does the 3D window go blank on resuming from sleep/lock?
I have a 3d window hosted inside a WPF program. This is written in C#, using SlimDX. It uses a D3DImage subclass to support dx10 & dx11 rendertargets, like this site recommends: http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/437/Direct3D-10-11-Direct2D-in-WPF.aspx

However, when I resume from sleep, or even lock & unlock the screen on Windows, the 3D window goes blank until I resize it. What is the appropriate way to mitigate this issue?

After resuming, but while the 3D window is still blank, I've confirmed:

* The window ActualWidth & ActualHeight have not changed
* The device is not null
* The backbuffer is not null
* The draw loop is still looping
* The blank screen is occurring after the unlock. To prove this I put a Thread.Sleep() in the Unlock handling code to purposely lock the UI thread. The 3D image was still visible until the thread.sleep period ended, then it went blank.

# Answer
> 1 votes
On resume from sleep/lock/ctrl-alt-delete the backbuffer needs to be reset. Because the backbuffer doesn't go grey until a halfsecond or so after resume, either find a way to detect that the backbuffer needs a reset, or wait an arbitrary amount of time. (Don't lock the UI!)

```
//Add to initialization code
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;

```

...

```
private async void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionUnlock)
    {
        await Task.Delay(1000);
        if (MBackBufferTex != null)
        {
            Md3DImage.SetBackBuffer11(MBackBufferTex);
        }
    }
}

```

# Answer
> 0 votes
I found a solution to this through vigorous searching, you can directly get the pointer reference from your bufferTexture within your D3DImage.

D3DImage has a non-public member called "\_pUserSurfaceUnsafe", when your D3DImage goes blank from ctrl+alt+delete, locking or sleeping then "\_pUserSurfaceUnsafe" loses its reference and becomes 0 (null pointer).

This part will return the reference to the field.

```
System.Reflection.FieldInfo surfaceReference = _d3dImage.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Single(pi => pi.Name == "_pUserSurfaceUnsafe");

```

This part will get you the value from your field reference.

```
object surfaceValue = surfaceReference.GetValue(_d3dImage);

```

You just have to test if the value is 0 or not equal to your bufferTexture and go from there. :)

---
Tags: directx, windows, slimdx
---


# Question
Title: Getting Display Name via Steam ID for Non-Friends
When using the Steamworks SDK (in C++), is there any way to get the display/persona name from the `CSteamID` object, even if we are not friends on Steam? Or is this possible for friends only?

In that case, when using a Steam leaderboard, how else should I display the nick names of the leaderboard entries in my game?

# Answer
You can use

```
SteamFriends.GetFriendPersonaName(steamUserID);

```

To get the user name even if they are not in your friends list. I have tested this out using Steamworks.NET in Unity.
> 2 votes

---
Tags: c++, steam
---


title: Glass Material for Unity 5

text:
# Question
Title: Glass Material for Unity 5
Anyone know how to make a glass material in Unity 5?

I can do metal and image textures, but not sure how to create a glass material.

A search on Google would not get me anything for Unity 5 so it must be fairly easy to do.

It's for a shower door and plane glass like this:

# Answer
> 13 votes
Here's few things i could gather up, hope this helps you. There's multiple ways to get this done. You can write shaders or if you don't mind about having very simple glass, you can use default shaders and some PNG magic.

1. Glass Shader made by **Alastair Aitchison**
2. Reflective transparent "Glass shader" made by **benoculus**
3. Unity asset store search: Glass
4. Free asset - Breakable glass

---

EDIT: As this is getting some attention, i decided to add step by step tutorial for very basic window/transparency

1. Create PNG image with transparency on places, where you need it.
2. Drag and drop it to your assets inside Unity
3. Drag it from assets to your gameObject, that you wanna use as glass
4. Select shader -\> Transparent -\> Specular ( or any of the choices, i liked specular )
5. Enjoy

---

I created simple 64x64 image with full background transparency and added black text on it

Then i imported it to unity ( dragged it ) and then dragged it over the cube i had there. After that, i selected transparent shader for it.

Results ( game is running )

After this, you could easily create PNG that has some scratches on it or other similar effects to make it look more real. You can even create borders with some color, that could look like a wood or metal. Try the different transparent shaders to find what looks best.

# Answer
> 6 votes
For making a glass material in Unity 5, using Unity shaders and materials is very easy. You need to:

1. Go to "Project" window and press "Create" new "Material".
2. Name it Glass and put it into "\_Materials" folder.
3. Assign Glass material to a game object sphere.
4. Select Glass material and in Inspector, change Render Mode to "Transparent".
5. Change the colour "Albedo" alpha down to 37 (will add transparency)
6. colour white
7. Change the Smoothness value to 0.973 (will add sharp reflection)
8. Change the Metalic value to 0.1 or 0.273 (will add more detail & shadow)
9. Source to "Metallic Alpha" (will add light in the reflection)
10. Set "Specular Highlights" and "Reflection" to enable

Done!

If you wish you can add textures that include alpha for much control. for example not clean glass.

# Answer
> 2 votes
The official Unity blog shared a link to a .zip package here that has example scripts and a shader that use Unity 5's new Command Buffers as an official solution to implement glass refraction and transparency.

# Answer
> 2 votes
I wrote a shader for glass (and translucency or custom lightmaps too) called Standard Plus. I think it does what you want. My glass has various controls on refraction, as well as fresnel. And on top of that, you can use thickness map to count for the model different thickness, producing much better results, because the thickness will affect not only the refraction but the glass color as well. And on top of that, it has the same functionality of the standard shader. Take a look! https://www.assetstore.unity3d.com/en/#!/content/93745

---
Tags: unity, shaders, textures
---


# Question
Title: How to implement glDrawElementsBaseVertex in OpenGL ES 3.0
I want to convert simple OpenGL project to Android native using OpenGL ES3.0, one of the functions which is not implemented is `glDrawElementsBaseVertex`, I have one VBO which contains many entries inside and known each offset and size, so how can I implement this function by `glDrawElements` method or is there another way?

# Answer
> 1 votes
(Disclaimer I haven't touched OpenGLES on Android and I definitely haven't done any benchmarking) I can think of two options here:

1. just have a really large index array with all the offsets in them. This takes up a lot more space, but it should still be small-ish (4 bytes per vertex maybe) compared to your vertex data.
2. For each mesh, Re-bind your attributes with different offsets. This now requires separate VAOs for each mesh to store the different attributes.

---
Tags: ndk, opengl-es3
---


title: Failed to initialise the LWJGL display

text:
# Question
Title: Failed to initialise the LWJGL display
I added the fix of adding this line "Dorg.lwjgl.opengl.Display.allowSoftwareOpenGL=true" to vm arguments, updated my drivers but nothing is working......my error message still remain same has shown in the image

# Answer
This error message is commonly caused by outdated video card drivers. To fix this, make sure you're using the latest version of LWJGL and have the latest version of your graphics card's video drivers installed.
> 1 votes

# Answer
First see Thomas's answer about upgrading your drivers, but there are also known issues with Java 64bit and OpenGL on Windows as well as known compatibility with EOL Intel Graphics chips. You haven't shown your configuration so we don't know what the issue is.

The solution for the first problem is to run the 32-bit version of Java, the solution for the second is an unsupported patch of the Intel HD Graphics driver. Usual caveats about installing drivers by some guy on the internet apply.
> 0 votes

---
Tags: java, lwjgl, slick, eclipse
---


# Question
Title: Getting the current 'Forward' direction Vector values into code and how to use them?
Im having some trouble visualising how the maths works for this particular problem. Back when i coded in 2d only this was often a stumbling point for mine even when only dealing with an x and y axis.

Here is the version of my current problem (but this is linked ot many other aspects of how my game will work , for example when I want to spawn a game object directly in front of the player for example):

1. Its a driving game where you have to drive along one long road until you get to the end. Of course there are going to be obstacles and enemies trying to stop you.
2. I'm using the Unity Standard Assets Car with some very small modifications to the control system only so far.
3. I want to proedurally generate the gameObjects (such as a ramp in the road, or an enemy at the side of road, or a cow in road for example).

4.I also would like a MPH counter (speedometer)

5. I can arrange all of this normally myself, but here's the thing, I can only do it on a straight road.
6. MY GAME NEEDS TO HAVE WINDING ROADS

So the way i normally calculate the MPH doesnt work I think, as it only works on 1 axis. If the players car is moving around a bend at 45d angle, then it would appear to be travelling much slower by my calculation than it actually is.

I think it must be calculated using the rotation, previousRotation, position, previousPosition and thats the route ive been exploring but i have failed to get anywhere and now my code is in a right mess. I am using the Unity Standard Car and I see in it's code that it has some math and uses the variable "forward", but im not sure how i can obtain a copy of that value, send it to my GameManager or Player script so that I can calculate where to put the obstacles etc onto the road exactly.

Most of the road is a nice straight road but there are some long bends too. I need some solid maths revision to get anywhere near calculating it myself and I just have a creeping feeling that half (if not more) of the work is already done for me inside this Unity Car Class.

I'll post the code here in case it helps: (Btw, its in the ApplyDrive method that im actually thinking the values i need are already there)

using System; using UnityEngine;

namespace UnityStandardAssets.Vehicles.Car { internal enum CarDriveType { FrontWheelDrive, RearWheelDrive, FourWheelDrive }

```
 internal enum SpeedType
 {
     MPH,
     KPH
 }
 public class CarController : MonoBehaviour
 {
     [SerializeField] private CarDriveType m_CarDriveType = CarDriveType.FourWheelDrive;
     [SerializeField] private WheelCollider[] m_WheelColliders = new WheelCollider[4];
     [SerializeField] private GameObject[] m_WheelMeshes = new GameObject[4];
     [SerializeField] private WheelEffects[] m_WheelEffects = new WheelEffects[4];
     [SerializeField] private Vector3 m_CentreOfMassOffset;
     [SerializeField] private float m_MaximumSteerAngle;
     [Range(0, 1)] [SerializeField] private float m_SteerHelper; // 0 is raw physics , 1 the car will grip in the direction it is facing
     [Range(0, 1)] [SerializeField] private float m_TractionControl; // 0 is no traction control, 1 is full interference
     [SerializeField] private float m_FullTorqueOverAllWheels;
     [SerializeField] private float m_ReverseTorque;
     [SerializeField] private float m_MaxHandbrakeTorque;
     [SerializeField] private float m_Downforce = 100f;
     [SerializeField] private SpeedType m_SpeedType;
     [SerializeField] private float m_Topspeed = 200;
     [SerializeField] private static int NoOfGears = 5;
     [SerializeField] private float m_RevRangeBoundary = 1f;
     [SerializeField] private float m_SlipLimit;
     [SerializeField] private float m_BrakeTorque;
     private Quaternion[] m_WheelMeshLocalRotations;
     private Vector3 m_Prevpos, m_Pos;
     private float m_SteerAngle;
     private int m_GearNum;
     private float m_GearFactor;
     private float m_OldRotation;
     private float m_CurrentTorque;
     private Rigidbody m_Rigidbody;
     private const float k_ReversingThreshold = 0.01f;
     public bool Skidding { get; private set; }
     public float BrakeInput { get; private set; }
     public float CurrentSteerAngle{ get { return m_SteerAngle; }}
     public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}
     public float MaxSpeed{get { return m_Topspeed; }}
     public float Revs { get; private set; }
     public float AccelInput { get; private set; }
     // Use this for initialization
     private void Start()
     {
         m_WheelMeshLocalRotations = new Quaternion[4];
         for (int i = 0; i < 4; i++)
         {
             m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
         }
         m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset;
         m_MaxHandbrakeTorque = float.MaxValue;
         m_Rigidbody = GetComponent<Rigidbody>();
         m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl*m_FullTorqueOverAllWheels);
     }
     private void GearChanging()
     {
         float f = Mathf.Abs(CurrentSpeed/MaxSpeed);
         float upgearlimit = (1/(float) NoOfGears)*(m_GearNum + 1);
         float downgearlimit = (1/(float) NoOfGears)*m_GearNum;
         if (m_GearNum > 0 && f < downgearlimit)
         {
             m_GearNum--;
         }
         if (f > upgearlimit && (m_GearNum < (NoOfGears - 1)))
         {
             m_GearNum++;
         }
     }
     // simple function to add a curved bias towards 1 for a value in the 0-1 range
     private static float CurveFactor(float factor)
     {
         return 1 - (1 - factor)*(1 - factor);
     }
     // unclamped version of Lerp, to allow value to exceed the from-to range
     private static float ULerp(float from, float to, float value)
     {
         return (1.0f - value)*from + value*to;
     }
     private void CalculateGearFactor()
     {
         float f = (1/(float) NoOfGears);
         // gear factor is a normalised representation of the current speed within the current gear's range of speeds.
         // We smooth towards the 'target' gear factor, so that revs don't instantly snap up or down when changing gear.
         var targetGearFactor = Mathf.InverseLerp(f*m_GearNum, f*(m_GearNum + 1), Mathf.Abs(CurrentSpeed/MaxSpeed));
         m_GearFactor = Mathf.Lerp(m_GearFactor, targetGearFactor, Time.deltaTime*5f);
     }
     private void CalculateRevs()
     {
         // calculate engine revs (for display / sound)
         // (this is done in retrospect - revs are not used in force/power calculations)
         CalculateGearFactor();
         var gearNumFactor = m_GearNum/(float) NoOfGears;
         var revsRangeMin = ULerp(0f, m_RevRangeBoundary, CurveFactor(gearNumFactor));
         var revsRangeMax = ULerp(m_RevRangeBoundary, 1f, gearNumFactor);
         Revs = ULerp(revsRangeMin, revsRangeMax, m_GearFactor);
     }
     public void Move(float steering, float accel, float footbrake, float handbrake)
     {
         for (int i = 0; i < 4; i++)
         {
             Quaternion quat;
             Vector3 position;
             m_WheelColliders[i].GetWorldPose(out position, out quat);
             m_WheelMeshes[i].transform.position = position;
             m_WheelMeshes[i].transform.rotation = quat;
         }
         //clamp input values
         steering = Mathf.Clamp(steering, -1, 1);
         AccelInput = accel = Mathf.Clamp(accel, 0, 1);
         BrakeInput = footbrake = -1*Mathf.Clamp(footbrake, -1, 0);
         handbrake = Mathf.Clamp(handbrake, 0, 1);
         //Set the steer on the front wheels.
         //Assuming that wheels 0 and 1 are the front wheels.
         m_SteerAngle = steering*m_MaximumSteerAngle;
         m_WheelColliders[0].steerAngle = m_SteerAngle;
         m_WheelColliders[1].steerAngle = m_SteerAngle;
         SteerHelper();
         ApplyDrive(accel, footbrake);
         CapSpeed();
         //Set the handbrake.
         //Assuming that wheels 2 and 3 are the rear wheels.
         if (handbrake > 0f)
         {
             var hbTorque = handbrake*m_MaxHandbrakeTorque;
             m_WheelColliders[2].brakeTorque = hbTorque;
             m_WheelColliders[3].brakeTorque = hbTorque;
         }
         CalculateRevs();
         GearChanging();
         AddDownForce();
         CheckForWheelSpin();
         TractionControl();
     }
     private void CapSpeed()
     {
         float speed = m_Rigidbody.velocity.magnitude;
         switch (m_SpeedType)
         {
             case SpeedType.MPH:
                 speed *= 2.23693629f;
                 if (speed > m_Topspeed)
                     m_Rigidbody.velocity = (m_Topspeed/2.23693629f) * m_Rigidbody.velocity.normalized;
                 break;
             case SpeedType.KPH:
                 speed *= 3.6f;
                 if (speed > m_Topspeed)
                     m_Rigidbody.velocity = (m_Topspeed/3.6f) * m_Rigidbody.velocity.normalized;
                 break;
         }
     }
     private void ApplyDrive(float accel, float footbrake)
     {
         float thrustTorque;
         switch (m_CarDriveType)
         {
             case CarDriveType.FourWheelDrive:
                 thrustTorque = accel * (m_CurrentTorque / 4f);
                 for (int i = 0; i < 4; i++)
                 {
                     m_WheelColliders[i].motorTorque = thrustTorque;
                 }
                 break;
             case CarDriveType.FrontWheelDrive:
                 thrustTorque = accel * (m_CurrentTorque / 2f);
                 m_WheelColliders[0].motorTorque = m_WheelColliders[1].motorTorque = thrustTorque;
                 break;
             case CarDriveType.RearWheelDrive:
                 thrustTorque = accel * (m_CurrentTorque / 2f);
                 m_WheelColliders[2].motorTorque = m_WheelColliders[3].motorTorque = thrustTorque;
                 break;
         }
         for (int i = 0; i < 4; i++)
         {
             if (CurrentSpeed > 5 && Vector3.Angle(transform.forward, m_Rigidbody.velocity) < 50f)
             {
                 m_WheelColliders[i].brakeTorque = m_BrakeTorque*footbrake;
             }
             else if (footbrake > 0)
             {
                 m_WheelColliders[i].brakeTorque = 0f;
                 m_WheelColliders[i].motorTorque = -m_ReverseTorque*footbrake;
             }
         }
     }
     private void SteerHelper()
     {
         for (int i = 0; i < 4; i++)
         {
             WheelHit wheelhit;
             m_WheelColliders[i].GetGroundHit(out wheelhit);
             if (wheelhit.normal == Vector3.zero)
                 return; // wheels arent on the ground so dont realign the rigidbody velocity
         }
         // this if is needed to avoid gimbal lock problems that will make the car suddenly shift direction
         if (Mathf.Abs(m_OldRotation - transform.eulerAngles.y) < 10f)
         {
             var turnadjust = (transform.eulerAngles.y - m_OldRotation) * m_SteerHelper;
             Quaternion velRotation = Quaternion.AngleAxis(turnadjust, Vector3.up);
             m_Rigidbody.velocity = velRotation * m_Rigidbody.velocity;
         }
         m_OldRotation = transform.eulerAngles.y;
     }
     // this is used to add more grip in relation to speed
     private void AddDownForce()
     {
         m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*
                                                      m_WheelColliders[0].attachedRigidbody.velocity.magnitude);
     }
     // checks if the wheels are spinning and is so does three things
     // 1) emits particles
     // 2) plays tiure skidding sounds
     // 3) leaves skidmarks on the ground
     // these effects are controlled through the WheelEffects class
     private void CheckForWheelSpin()
     {
         // loop through all wheels
         for (int i = 0; i < 4; i++)
         {
             WheelHit wheelHit;
             m_WheelColliders[i].GetGroundHit(out wheelHit);
             // is the tire slipping above the given threshhold
             if (Mathf.Abs(wheelHit.forwardSlip) >= m_SlipLimit || Mathf.Abs(wheelHit.sidewaysSlip) >= m_SlipLimit)
             {
                 m_WheelEffects[i].EmitTyreSmoke();
                 // avoiding all four tires screeching at the same time
                 // if they do it can lead to some strange audio artefacts
                 if (!AnySkidSoundPlaying())
                 {
                     m_WheelEffects[i].PlayAudio();
                 }
                 continue;
             }
             // if it wasnt slipping stop all the audio
             if (m_WheelEffects[i].PlayingAudio)
             {
                 m_WheelEffects[i].StopAudio();
             }
             // end the trail generation
             m_WheelEffects[i].EndSkidTrail();
         }
     }
     // crude traction control that reduces the power to wheel if the car is wheel spinning too much
     private void TractionControl()
     {
         WheelHit wheelHit;
         switch (m_CarDriveType)
         {
             case CarDriveType.FourWheelDrive:
                 // loop through all wheels
                 for (int i = 0; i < 4; i++)
                 {
                     m_WheelColliders[i].GetGroundHit(out wheelHit);
                     AdjustTorque(wheelHit.forwardSlip);
                 }
                 break;
             case CarDriveType.RearWheelDrive:
                 m_WheelColliders[2].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 m_WheelColliders[3].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 break;
             case CarDriveType.FrontWheelDrive:
                 m_WheelColliders[0].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 m_WheelColliders[1].GetGroundHit(out wheelHit);
                 AdjustTorque(wheelHit.forwardSlip);
                 break;
         }
     }
     private void AdjustTorque(float forwardSlip)
     {
         if (forwardSlip >= m_SlipLimit && m_CurrentTorque >= 0)
         {
             m_CurrentTorque -= 10 * m_TractionControl;
         }
         else
         {
             m_CurrentTorque += 10 * m_TractionControl;
             if (m_CurrentTorque > m_FullTorqueOverAllWheels)
             {
                 m_CurrentTorque = m_FullTorqueOverAllWheels;
             }
         }
     }
     private bool AnySkidSoundPlaying()
     {
         for (int i = 0; i < 4; i++)
         {
             if (m_WheelEffects[i].PlayingAudio)
             {
                 return true;
             }
         }
         return false;
     }
 }

```

}

As I say that is just standard Unity Assets code, but particularly in the ApplyDrive function i see the forward variable that I think will be useful (or hope :))

Any help on the best way to approach this kind of problem is massively appreciated. Sorry for the long-winded post. Thanks again for reading

# Answer
`m_Rigidbody.velocity` is your movement vector.
`m_Rigidbody.velocity.magnitude` is the speed.
`m_Rigidbody.velocity.normalized` would be the normalized direction.

Note that units are in meters per second, which is why there's the `CurrentSpeed` property that returns it in miles per hour.

```
public float CurrentSpeed{ get { return m_Rigidbody.velocity.magnitude*2.23693629f; }}

```

---

> How would I use the normalize value above, to put into my GameManager class for example to say, when car is at Z position 150 on map, add Ramp 30 units IN FRONT OF THE CAR.

stop isolating the Z coordinate and use the entire vector!

```
class Car {
    Vector3 position;
    Vector3 velocity;
}

Vector3 ramp_position = car.position + 30.0f * car.velocity.normalized;

```

This says "start from the cars position, and offset it by 30 units in the direction of the car's velocity (i.e, which way it's moving)"
> 1 votes

---
Tags: unity, c#, vector, trigonometry
---


title: Vulkan rendering lots of objects

text:
# Question
Title: Vulkan rendering lots of objects
I'm wanting to render multiple objects on a screen and in some cases several of each object. I'm not sure what the best method of doing this is and was wanting some advice. The only way I can think of doing this is having X Command Buffers for each model I want to render and store all draw requests for that model inside, then submit them when I require the draws.... Would this work or is there a better solution?

# Answer
> 2 votes
Submitting Command Buffers is not a bad thing to do in Vulkan. So long as you're submitting them in logical batches together you'll find that it's plenty fast to submit tons of commands. However if you need more speed, "geometry instancing" can be very fast for drawing lots of objects. Note that you may not need to in the first place since submitting lots of command buffers is totally fine; profile first and optimize later.

Regarding instancing here are some resources:

This reference here is for OpenGL but the principles still apply.

If you want a Vulkan specific example Sascha Willems has a code sample on Github but it doesn't have the in-depth explanation as the previous link.

---
Tags: vulkan
---


# Question
Title: How to stop several coroutines running on array of game objects
In the code below, I am running a coroutine on each element of an array of game objects. How can I stop running the `FadeToForEnemy` coroutine on each game object?

```
    IEnumerator EnemyCycle()    {
    while (isRepeating)
    {

        for (int j = 0; j < enemies.Length; j++) {

            Enemy currentEnemy = enemies [j];
            var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, 1f, currentEnemy.gameObject, false));

        }

        yield return new WaitForSeconds (hdTime);

        for (int j = 0; j < enemies.Length; j++) {

            Enemy currentEnemy = enemies [j];
            var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
            var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, 1f, currentEnemy.gameObject, true));

        yield return new WaitForSeconds (srTime);

        }
    }
}

```

**UPDATE**

I tried stopping the coroutines in the following but the cycle of fading in and out just continued.

```
public void StopEnemyCycles ()  {
    for (int i = 0; i < enemies.Length; i++) {
        enemies [i].StopAllCoroutines ();
    }
    StopCoroutine ("EnemyCycle");

}

```

Also below is `FadeToForEnemy`:

```
    IEnumerator FadeToForEnemy(Material material, float targetOpacity, float duration, GameObject gameObj, bool isEnabled) {

    // Cache the current color of the material, and its initiql opacity.
    Color color = material.color;
    float startOpacity = color.a;

    // Track how many seconds we've been fading.
    float t = 0;
    if (isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }

    while(t < duration) {
        // Step the fade forward one frame.
        t += Time.deltaTime;
        // Turn the time into an interpolation factor between 0 and 1.
        float blend = Mathf.Clamp01(t / duration);

        // Blend to the corresponding opacity between start & target.
        color.a = Mathf.Lerp(startOpacity, targetOpacity, blend);

        // Apply the resulting color to the material.
        material.color = color;

        // Wait one frame, and repeat.
        yield return null;

    }

    if (!isEnabled) {
        gameObj.GetComponent<BoxCollider2D> ().enabled = isEnabled;

    }
}

```

I have several groups of enemies, each group fades in and out at the same time.

# Answer
> 1 votes
you need to go nuclear and do

```
StopAllCoroutines();

```

or save the coroutines that you're starting.

```
var all_coroutines = new List<IEnumerator>();
for (int j = 0; j < enemies.Length; j++) {
        Enemy currentEnemy = enemies [j];
        var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
        var fade_coroutine = FadeToForEnemy(_myMaterial, 1f, 1f, currentEnemy.gameObject, true);
        all_coroutines.Add(fade_coroutine);
        var _currentFade = StartCoroutine(fade_coroutine );
}
..
foreach(IEnumerator coroutine in all_coroutines) {
    StopCoroutine(coroutine);
}

```

---
Tags: unity
---


# Question
Title: Unity engine memory usage issue - taking up more than it should
I'm making a 2D game that consists mostly of *sprites*. As a lot of them were too large in file size, I swapped them into *meshes with unlit materials **without** textures*. Now, The problem is that Unity by default, just opening a blank scene, uses **20 MB** of texture memory according to the profiler.

So I checked instantiating 100 of my sprites (294 kb each), where the profiler showed **100MB** used.

After that I had only those meshes in the scene, still 100 pieces, vertex count **124** each, tri count **47**. The memory usage was still around **100 MB**, texture usage **20 MB**

Lastly I instantiated 100-100, so the sprites and meshes together. I got around **106 MB** used memory.

This is my used memory with the **sprites**:  And this is my used memory with the meshes.  Now, as far as I know the meshes should rock in terms of memory as they are low res and have no textures attached. Could someone tell me what's going on, why are my meshes worse than using sprites? And how to sort this out?

# Answer
To anyone reading this, I got help via Unity bug report and they revealed the the Profiler reflects *everything* regarding Unity, not just my game. The engineer made a build and profiled my game that way - the mesh setup is **waaay** more effective. Use that if you have the chance.
> 0 votes

---
Tags: unity, performance, optimization, memory, profiler
---


title: Unity - blur only selected layers

text:
# Question
Title: Unity - blur only selected layers
I'm messing around with Unity 2017's post processing tools while making a 2D game that benefits from the parallaxing effect using a perspective camera. Please note that the game is mostly made using *sprites*.

Now, I have a **playerGround**, a **backGround** and a **foreGround**. I wish to blur the background and foreground only but not the playerground. I'd like to know how to do this as playing with the focal length didn't do anything, everything receives the same blur amount regardless of the distance from camera.

# Answer
> 0 votes
You could just use one camera for the layers you'd like to blur, apply post process to that one, and another camera for the unblurred layers. Parent one to the other camera, only move the parent, and set the camera depth to match.

---
Tags: unity, post-processing, image-effects
---


# Question
Title: What is the universal "Distance Point" for human vision?
I'm not sure if this is the technical term, but I'm asking: At what rate do things scale bigger and smaller as they move toward and away from the human eye?

I know the equation for the linear perspective grids below are,

(size changed by this %) = 5/((distance to object) + 5) for the grid on the left
and
(size changed by this %) = 3/((distance to object) + 3) for the grid on the right

The '3's and the '5's come from the distance from the distance point to the vanishing point. On the grid on the right the objects smaller at a bigger rate as they move back than they do on the grid on the rate that has a distance point of 5.

for example: a circle with a 1' diameter at (distance to object) = 0
will be 0.5' at 5' away because...
0.5 = 5(5 + 5) = 5/10 = 1/2

I know one point perspective is not nearly the most accurate model, but I'm only interested is calculating the size of objects depending on their size, or vice versa. Maybe you have a better equations that scales objects the same way the eye perceives.

Right now I only know what it isn't. It's not depth of field because that has to do with what's in focus. It's not the range of vision in terms of degree or depth perspective because the eye(s) can see things shrink at the same rate with one eye looking at things going straight away from me.

In both of my grids the hieght from the horizon is 5' but things scale bigger and smaller at the same rates away from you whether you're on the ground or in a hot air balloon.

I suppose whatever the different setting there is between a fish eye and my eye is what I'm asking.

So, please. What is the distance point for the human eye?

# Answer
> 2 votes
What you are referring to what is usually referred to as the "field of view" angle. The concept of FOV angle approaches the issue from the opposite direction, though. It defines how much width is visible at what distance. At a distance of `d`, the vertical width which is visible on the screen is `d * tan(fov / 2) * 2`. That means the screen-width of a circle of radius `r` would be `r / (d * tan(fov / 2) * 2)`.

You can zoom in and out by changing the FOV angle. Sniper scopes in first person shooters are often implemented that way.

What FOV angle is the "natural" one is a matter of discussion. People's preferences are found anywhere between 45° and 90°. If you want to determine the ideal FOV angle in a physical way, you would need to know the physical width of the player's monitor and the distance between the monitor and the player's eyes.

# Answer
> 2 votes
There isn't one: Human eyeballs are round and heads pivot, so they don't have a flat projection plane.

When rendering, the proper Field Of View (FOV) angle for projecting into the flat screen plane depends on the human eyeballs distance from the screen and the size of the screen.

You can let the users change the FOV angle to match their gaming setup if they wish to and guesstimate the proper default value from the average screen size and average eye distance.

A mobile game may need a different default FOV from a TV console game or a PC desktop/laptop game.

---
Tags: rendering, virtual-reality, augmented-reality
---


# Question
Title: How can I prevent false score reports to global highscore tables?
Browser and mobile games commonly have global highscore tables. It's also common for those tables to contain scores of 2,147,483,647 — where people have figured out the webservice call that reports scores and used it to record a fictitious score.

For simple puzzle games, we can defend against this by including a record of every move the player made (and any random seeds used to generate the level) with the score-reporting call. The entire game can then be reproduced and verified on the server.

However, this quickly becomes infeasible for anything larger than Pac-man.

How else can cheating of this kind be prevented?

# Answer
> 10 votes
The internal system we used for Moblox (later replaced with OpenFeint) worked like this:

* Send a JSON message over plain HTTP (not HTTPS). Include a MD5-hash of all fields plus a magic string.
* On the server, check the integrity of the message with the same operation.

To crack the system, you'd have to find this magic string. It is possible with reverse engineering, but painful.

OpenFeint, ScoreLoop and CocosLive all use the same trick, but with HTTPS. Very easy to implement.

# Answer
> 21 votes
While you're right that it's not always feasible to send entire replays to the server for complex games, a similar system can be used by having the server periodically (and semi-randomly) ask the client for some part of its state, while the game is running.

For example, in an FPS, every minute you could ask "How many kills do you have?", "Where are all the enemies?", etc. If the client doesn't come back with a reasonable answer to a challenge in a reasonable amount of time, they are cheating.

Of course, this only works if the game is online during the entire play session. Since the goal here is to be able to upload to an online leaderboard, I think that's reasonable - don't kick the player out of the game if they answer wrong, just don't let them on the score list.

I would encourage you to reconsider sending replays however. All you really need is the initial random seed and timestamped input. This should really be a few hundred KB at most. Many arcade games do this already to save replays for player review purposes; having your server validate these might not be trivial, but it prevents all kinds of cheating except botting.

# Answer
> 10 votes
You can limit the most flagrant of abuses by monitoring the highest results in the top score table. Depending on your game, you may have a "perfect score," above which any score must be fraudulent. If not, you can calculate the lowest "impossible score;" can the player shoot 10 shots per second, the game lasts 1 minute, and each killed enemy is worth 100 points? Then any score higher than 60,000 must be fraudulent.

You can also help mitigate the problem by sending along some metadata; not the full game history, as you describe, but just the components that make up the score. Say: score 60000, 500 enemies killed, and one bonus item grabbed. You can then perform simple checks. This is "security through obscurity," and therefore not secure at all, but it helps eliminate the most naive of attackers.

# Answer
> 6 votes
Ultimately you can only rule out impossibly high scores, because the rest are (by definition) merely implausible, and thus might be a legitimate (and awesome) player.

Otherwise you have to rely on obfuscation techniques (such as encryption, and sending other stats beyond just score).

You could also send the score periodically as the game is being played, which would add another level of complexity to cheating - i.e. the server can decide if the game has been played long enough to warrant a particular score, and also ensure that enough intermediate reports were received during the play-time (just don't make it 100% or the train going into a tunnel on my way home will result in my throwing the phone out the window).

Ultimately someone will find a way to break it though, so don't kill yourself trying to stop them.

# Answer
> 6 votes
I added a quick/dirty high score table to a project of mine a while back and not being at all versed in internet security/etc it turned out sort of flawed. Surprisingly, with nearly 1,200,000 recorded scores, I've only had maybe 5 or 6 occasions of batches of blatantly incorrect scores reaching the top of the board. Most of the scores even looked more like a glitch in the game, than a true "hacking".

So I guess an important point is: **make sure your game's scoring system is airtight**, or at least do some really good score feasibility checking; now, this game I'm talking about was a Ludum Dare 48hr entry, so it wasn't the most stable thing around.. but on the whole I think it's often more likely that the casual player will discover/exploit an ingame glitch than having someone directly "hack" the leaderboard.

That said, I'm working on a rewrite of this project right now, and I'm going all out with the obfuscation. I won't go into too much detail, but I basically have all scores submit a key value based on a bunch of random values and hashing and a magic string, then any score that passes that check and is high enough to make the actual "Top X" leaderboard has to pass another round of validation (this time with an expiring key value generated on the server end, and more thorough feasibility checks).

**I'd also advise using a packet tracer of some sort** to test out what sort of things are visible (I was originally doing a much simpler verification that meant someone could use a packet tracer to find and duplicate an uploaded score's http request, without knowing the magic string or anything (meant you needed a legit score first, but you could send duplicates of that score as much as you wanted..)). I used Wireshark for testing this.

Huh, this turned out a bit long, but hopefully it helps...

# Answer
> 3 votes
I am not an expert in this field but if I were you, I will try to encrypt the score with an key embedded in the your code. Those people will need to apply reverse engineering over your code instead of the plain text used for the web-services.

# Answer
> 1 votes
Speedruns are basically recording of every keystroke, and they are recording about a WHOLE game. So, yes, you can record the whole game, it's not unfeasible. *Any* other way to do that is crackable through reverse engineering (I can't stress it enough: you're not adding security, you're adding obscurity).

Still, even if you do it this way they could actually submit a speedrun. You can do nothing to prevent that.

# Answer
> 1 votes
While you're at it, there's the question of whether a high score is simply a player who found an exploit (for example, if some things in the game give a score penalty, and a bug causes a negative score to "wrap around" to become highly positive... or just a player who finds a certain game condition like a safe spot on the board where they can just sit there and not have to worry about losing, indefinitely).

In order to tell the difference between a hack and a game exploit, uploading at least some play data would be good. It'll help you fix the exploits, at least.

For some games (particularly turn-based ones), you can actually have the game played through the server, where all of the game logic exists on the server side and the client is just an interface. This not only makes score hacking a lot harder, but it also enables you to log all player actions on the server trivially, and thus replay any game at any time. I realize for something like a twitch action shooter, this might be impractical.

# Answer
> 1 votes
Make all randomness origin from one seed and store the input for every frame. Whenever you have a claimed high score (say top 50), send the seed and the full input to the server. Replay the game on the server and update the leaderboard if you get a high score.

If you consider this unfeasible for more sophisticated games because of the size of the request, take a look at this example.

Say the game has 8 button input (1 pad and 4 buttons) and runs at 60fps. A one hour game input can be transmitted with 3.6KB without compression. Your session will probably have less than one hour and compression should shrink that by a lot, because human input has a lot of redundancy.

The challenge is making the game deterministic, playable from recorded input and executable on the server.

# Answer
> 0 votes
Never implemented this before but...

Send scores incrementally with timestamps. This gives you a log to see how often the score improved as well as a way to trace the highscore's "momentum".

You would then set milestones/criteria for your scores.

For example: A score greater than 20,000 can not arrive in first 20secs of a game. An score greater than 250,000 can not arrive without an entry greater than 200,000.

This is not exactly the same as sending a game state, but close to it.

Side Benefit: Think of all the useful game play statistics you would get from this. Someone would prob pay good money for that.

---
Tags: mobile, web, security, leaderboards, anti-cheat
---


# Question
Title: Anchor a health bar to a character/enemy
I have a game I'm working on where the player can see the health bars of the player's avatar and other creatures in the game. I want this health bar to always follow the character/creature around. However, I can't figure out how to do this. I thought having the position change when the respective object moved would do the trick, but apparently, it doesn't. When watching the health bar's transform, however, it shows that it is moving with it's respective object but I don't see it on the game screen. Can anyone explain how I go about accomplishing this? Here's the Dropbox link to the project.

**HealthBar Script**

```
public class EnemyHealthBar:MonoBehaviour{
    public Texture2D healthBar;
    public Texture2D health;
    public Rect healthBarPosition;
    public Rect healthPosition;
    public GameObject monster;

    void Start(){
    }
    void Update(){
        transform.position = new Vector3(monster.transform.position.x, monster.transform.position.y, monster.transform.position.z);
        Debug.Log(transform.position);
    }
    void OnGUI(){
        GUI.DrawTexture(healthBarPosition, healthBar);
    }
}

```

Video of what's currently happening

Dropbox Link

# Answer
Based on the discussion above, I'd recommend moving over to the new UI system for content like this. It will be a bit of an adjustment at first, but it gives you a lot of flexibility:

* Using UI Image components, you can create scalable health bars, using the "sliced" type to get rounded corners that don't distort or get cut off as the bar changes size, or the various "filled" methods to reveal a portion of the bar (including circular bars if you wanted)
* You can set up animations and effects on the bars in the editor, instead of needing to describe every behaviour in code within the `OnGUI` method. This also makes it more straightforward for a team to collaborate on UI, since it's not bottlenecked in one file
* When you need different variations on the UI (eg. a boss character who needs a super-fancy-looking health bar) you can create them as new prefabs in the editor, instead of needing to maintain multiple copies of your UI-drawing script for each case

There's tons of tutorials out there for creating the health bar, so I won't go into too much detail about the asset setup here, focusing instead on the script to position it correctly.

So, I'll assume you've set up...

* A UI Canvas that's containing your health UI, set to either Screen Space Camera or Screen Space Overlay modes (World space would be handled differently, if you want to go there)
* A GameObject child of your canvas representing your health bar. It probably contains one or more child objects of its own for the various visuals (eg. bar frame, bar fill, character name text, status effect icon...)

Now, we can attach this script to the health bar GameObject:

```
public class UIAnchor : MonoBehaviour {

    // Assign this to the object you want the health bar to track:
    public Transform objectToFollow;

    // This lets us tweak the anchoring position in the object's local space
    // eg. if you want the bar to appear above the unit's head.
    public Vector3 localOffset;

    // This lets us tweak the anchoring position in our canvas space
    // eg. if we want the UI to sit off to the right on our screen.
    public Vector3 screenOffset;

    // Cached reference to the canvas containing this object.
    // We'll use this to position it correctly
    RectTransform _myCanvas;

    // Cache a reference to our parent canvas, so we don't repeatedly search for it.
    void Start () {
        _myCanvas = GetComponentInParent<Canvas>().GetComponent<RectTransform>();
    }

    // Use LateUpdate to apply the UI follow after all movement & animation
    // for the frame has been applied, so we don't lag behind the unit.
    void LateUpdate () {

        // Translate our anchored position into world space.
        Vector3 worldPoint = objectToFollow.TransformPoint(localOffset);

        // Translate the world position into viewport space.
        Vector3 viewportPoint = Camera.main.WorldToViewportPoint(worldPoint);

        // Canvas local coordinates are relative to its center,
        // so we offset by half. We also discard the depth.
        viewportPoint -= 0.5f * Vector3.one;
        viewportPoint.z = 0;

        // Scale our position by the canvas size,
        // so we line up regardless of resolution & canvas scaling.
        Rect rect = _myCanvas.rect;
        viewportPoint.x *= rect.width;
        viewportPoint.y *= rect.height;

        // Add the canvas space offset and apply the new position.
        transform.localPosition = viewportPoint + screenOffset;
    }
}

```

This does have the effect of separating the health bar from the character object/script, which can be awkward when you're spawning characters at runtime, as you need to do a little work to spawn their health bar too and ensure it's wired-up correctly. Two approaches you can consider:

* Add the health bar as a child of your character prefab, so they get spawned together. Modify the `Start` method above so instead of searching for a parent canvas, we find the main UI canvas in the scene and re-parent the health bar to it during initialization. Since both exist in the same prefab, you can have all their dependencies wired-up in advance (though without nested prefab support, this might mean you end up duplicating assets).
* Have your character's health component expose a variable for a health bar prefab. During this health script's `Start` method, it spawns an instance of this prefab and parents it to the scene's UI canvas. It will also need to handle wiring-up the health bar to follow it, and its own health update to scale the right part of the health bar.
> 6 votes

# Answer
I would recommend that you make a new `Canvas` object as a child of the player object and in its `Canvas` component set the `Render mode` to **World space**. Then create your `Healthbar` as the child of this canvas.
> 3 votes

# Answer
I don't have enough reputation to comment, but expanding on DMGregory, you can use the following to keep it in a prefab and have it automatically find the transform and then reparent to the canvas:

```
    void Start () {
    objectToFollow = transform.parent;
    _myCanvas = GameObject.Find ("Canvas").GetComponent<RectTransform>();//GetComponentInParent<Canvas>().GetComponent<RectTransform>();
    transform.SetParent(_myCanvas, false);
}

```

The only problem is that since they are GUI objects, they show through everything, so you can spot an enemy a mile away by his health bar.
> 0 votes

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


# Question
Title: Should I avoid constructors/destructors in C++ when using custom allocators?
I'm currently building my first 2D game engine and have reached a point where some large-scale tests have shown that some form of custom memory management would be beneficial (object pools).

So I created an object pool but got stuck on the problem of calling the constructor and destructor of the objects allocated from that pool.

So I read this: http://www.scs.stanford.edu/~dm/home/papers/c++-new.html

This seems to be a common problem when using custom allocators and there seems to be no nice solution to it within C++. I've also read on some other place that one should avoid "new" like the plague when creating a game engine. So, if that's the case, should I avoid constructors and destructors altogether? Should I fall back to a Init/Shutdown mechanism for my objects?

Appreciate any advice.

EDIT: Besides the correct answer below, one solution to the problem (also mentioned by mikosz) that also allows the use of non-default constructors can be found here: http://anki3d.org/cpp-allocators-for-games/

# Answer
New and delete are only an issue when used excessively (10,000+ times per frame).

This usually means an engine architectural redesign is in order. Allocation pools rarely fix this.

But if you must:

## You can use the placement new to call the constructor on an allocated pool object and then call the destructor explicitly when the object gets released back into the pool.

Create a pool:

```
class MyPool {
public:

  ...

protected:
  char *pool;
  size_t pool_size;

  // some way to keep track of free indices here
}

MyPool::MyPool() {
  pool_size = 100;
  pool = new char[sizeof(MyClass) * pool_size];
}

```

Construct an object and return it:

```
MyClass *MyPool::MyAlloc() {
  size_t index = FigureOutWhichIndexIsAvailableAndMarkAsUsed();

  // call constructor using placement new
  new( ((MyClass *)pool) + index ) MyClass();

  // return pointer to constructed object
  return ((MyClass *)pool) + index;
}

```

Use object in pool...

Destroy object:

```
void MyPool::MyFree(MyClass *pool_object) {

  //figure out index of object
  size_t index = pool_object - (MyClass *)pool;

  assert(index < pool_size); // check for error (pointer outside of pool range)

  // call destructor on object explicitly
  pool_object->~MyClass();

  MarkIndexAsFreeSoItCanBeReusedLater(index);
}

```

Then delete entire pool storage when your container gets deleted:

```
MyPool::~MyPool(){
  assert(EveryObjectIsFree());

  delete[] pool;
}

```
> 3 votes

---
Tags: c++, architecture, memory-efficiency
---


# Question
Title: I have problem understand instantiating new objects in Unity at runtime , help please :)
Hi again you fine folks.

So I'm making a driving game and there is going to be some cows in the road you have to dodge.

Currently I've laid 3 spawnpoints in the form of flat cubes, with the following script attached to each of them. (The reason I am manually laying the spawn points out myself is that the road is very windy, and has steep hills etc , and I was struggling to find a way to prodecurally place them on the road exactly at correct height etc.

Here is the code im using for these spawn points. For some reason I am getting all 3 cows spawn on the first spawn point, instead of just one. I haven't driven the car thru to the other 2 spawn points, id guess there'd be 3 cows at each of them. (I have to actually build to my phone to get that far due to the controls being for mobile not PC):

```
public class CowSpawn : MonoBehaviour {
public GameObject bullPrefab;
public float spawnChance;
bool willSpawn = false;

private GameObject bull;

// Use this for initialization
void Start()
{
    if (Random.value < spawnChance)
    {
        willSpawn = true;
    }

    bull = (GameObject)Instantiate(bullPrefab);
    bull.transform.position = GetComponent<GameObject>().transform.position;

}

// Update is called once per frame
void Update () {

}

```

}

# Answer
> -1 votes
No, sorry I have just found the answer. I am trying to access a GameObject that doesnt exist. I just needed to remove GetComponent() completely, as I was already 'in' that GameObject with that script

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


# Question
Title: Why is my light not working as expected in OpenGL 2.0 using GLSL?
First off, this is a Uni assignment, but the lecturer is stumped too.

The light (attached to the mouse) only works when inside of the object (a sphere in this case). I've tried multiplying the normals of the sphere by -1 and the distance of the light to the sphere by -1 also. I have no idea what the cause of this is.

Here is the fragment shader:

```
const float     lightWeighting = 0.75;
const float     textureWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
//varying   sampler2D   HeatValues

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  float distToLight = length(t); //I belive this is where it is going wrong

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  gl_FragColor = lightingColour;

}

```

Vertex Shader as requested:

```
//I am surprisingly important

uniform float   Intensity;
varying vec3    Normal;
varying vec3    Vertex;
varying vec2    texCoord;

void main(void)
{
    gl_Position     = ftransform();
    texCoord    = gl_MultiTexCoord0.xy;

    Normal = vec3(gl_Normal.xyz);
    Vertex = vec3(gl_Vertex.xyz);

}

```

Normals are as loaded from the obj file which was produced with blender

# Answer
> 0 votes
The distance from the light calculation was the issue.

I still get illumination from inside of the object, but I'm not bothered about that.

Here is the fragment shader with the change:

```
const float     lightWeighting = 0.75;
const float     textureWeighting = 0.25;

const float     PI = 3.14;
const float     lightIntensity = 1.0;
const float     constFudge = 0.025;
const float     linearFudge = 0.025;
const float     quadraticFudge = 0.05;

float rend  = 250.0;
float rstart = 50.0;

uniform float       Intensity;
uniform sampler2D   grabTexture;
//varying   sampler2D   HeatValues

varying vec3        Normal;
varying vec3        Vertex;
varying vec2        texCoord;

void main(void)
{
  vec3 pigPos = Vertex;
  vec3 normPigPos = normalize(pigPos);

  vec3 lightPos = vec3(gl_LightSource[0].position.xyz);

  vec3 normLightPos = normalize(lightPos);

  float effectiveIntesity;

  vec3 normNormal = normalize(vec3(Normal.xyz));

  vec3 t = vec3(pigPos - lightPos);

  ////////////////////////////
  // THE FIX
  ////////////////////////////

  float distToLight = length(t)/100; //the divide by 100 fixed it (I probably need to make the light brighter)

  ////////////////////////////
  // END OF FIX
  ////////////////////////////

  float d = dot(normNormal.xyz, normLightPos.xyz);
  if(d > 0.0)//facing the light
  {

    effectiveIntesity = d*lightIntensity * (1.0/(constFudge + (linearFudge*distToLight) +(quadraticFudge*distToLight*distToLight)));

  }
  else
  {
    effectiveIntesity = 0.0;
  }

  //TODO: change the colour of the pixel
  vec4 lightingColour = vec4(vec4( 1.0 ) * effectiveIntesity); //TODO: improve

  gl_FragColor = lightingColour;

}

```

# Answer
> 0 votes
This may not be the whole issue, but I do see some problems

```
float d = dot(normNormal.xyz, normLightPos.xyz);

```

`normLightPos` looks pointless to me - it is the direction of the light from the center of the world

what you really want (I think) is

```
float d = dot(normNormal.xyz, normalize(t));

```

to compare the surface normal with the angle of the light.

I'd also strongly recommend trying this out in isolation from the distance/falloff check - as in, using "d" directly as the brightness of a pixel.

When you have good lighting from just the angle, add in linear brightness falloff - then afterwards upgrade to the more complex falloff you are attempting

It may help testing to have several spheres scattered around the scene, so you can see the effects of the lighting on nearby and far-off objects

---
Tags: opengl, glsl, lighting
---


# Question
Title: Making dialogue different with each playthrough
I'm making a little demo game where roughly half of the NPCs in a little town have a profession, as well as a personality. I'm trying to have the game procedurally create dialogue, so when an NPC is talking about what they do, they describe it with some personality.

So for example, I may have a farmer who's an over achiever. He may have dialogue like this: "I farm from sun up to sun down. And I have the most cows around!" In another incarnation, a brainiac farmer may say, "Hi, my farm has exactly five cows, and is run very efficiently."

In the demo, the town will be procedurally generated, with a small number of townsfolk (around ten or twelve). Some will be peasants, others will be farmers. One or two will be merchants/shopkeepers. When the player talks to some of these folk, the NPC may greet the player and say something about what they do. Or they may describe themselves, as well as something about their town. On occasion, the NPC will also say something about their family.

I have thought of using a templating system, where it would fill in some of the dialogue. But I would like the sentences to vary with each playthough. I have also thought of using parts of speech so as to create sentences. The problem with using parts of speech (at least with using NLTK) is that I need some form of grammar to string them all together, and this is mainly meant for a small demo. Another option is to use a natural language generator (NLG), but that's getting into the realm of advanced AI. And I would like to steer away from that.

So should I use a templating system for the dialogue (I have tried using Rant, but I got into some really complicated syntax with that)? Or, should I use a dialogue system that uses parts of speech, and strings them together with some kind of grammar?

For what it's worth, I'm restricting the NPCs to a group of personalities. Also, some of what they say is based upon their stats. So if their intelligence is low, yet their charisma is high, maybe they'll be a xenophobe, or an over achiever.

# Answer
> 7 votes
There's a great GDC Talk by Elan Ruskin of Valve on what they call "AI-Driven Dialogue through Fuzzy Pattern Matching" or "Rule Databases for Contextual Dialogue and Game Logic" \- it's the system that powers contextual dialogue in the Left4Dead games, for example.

The core idea is that you can tag your dialogue with arbitrarily deep criteria for when it would be relevant/appropriate, and then rapidly search your dialogue database for the best dialogue to match any particular moment that arises in your game.

So rather than a fixed matrix like n lines for each combination of profession + personality template times the number of distinct conversation beats, you can mix and match criteria as needed.

It might look something like this:

```
// Very generic rule, can act as a catch-all if no other combination matches.
[Event = Greeting] "Hello"

// Adding an extra condition can start to make more characterful lines,
// while still having a broad pool of matches that different NPCs can share.
[Event = Greeting, NPC Has Trait Friendly] "Howdy!"

// Breaking up conversations into beats lets you mix & match lines for more combinations
[Event = Greeting Follow-Up, NPC Profession = Farmer]
 "Just taking a break from the fields"

// You can of course mix and match this with procedural replacement
// to add more specificity to the lines
[Event = Greeting Follow-Up, NPC Profession = Farmer]
  "{Crop}'s coming in well, don't you think?"

// You can also key off of gameplay state variables
[Event = Greeting Follow-Up, Times Talked to This NPC = 1]
"I don't think we've met. I'm {NPC Name}"

// Stacking more can create more specific modular lines...
[Event = Greeting Follow-Up, Times Talked to This NPC > 1, NPC Has Trait Friendly]
"Nice to see you again, {Player Name}"

// Expressing fairly unique conversation situations in a reusable way.
[Event = Greeting Follow-Up, Times Talked to This NPC > 1,
 NPC Has Trait Friendly, NPC Has Trait Forgetful]
"Nice to see you again, um... er... sorry, what was your name again?"

```

Where this can become super powerful is that a line of dialogue that's matched the current gameplay context and played can then set its own variables into the gameplay state, or fire off its own conversation beat event to direct where the conversation goes from there (which can itself have any number of context-sensitive matches...)

So instead of writing explicit trees of dialogue, you effectively create a set of connection points between them, and they assemble themselves on the fly in reaction to the gameplay context in the moment, like proteins folding & linking according to the makeup of their chemical soup.

I recently implemented this in Unity for a narrative game, and so far I'm loving the flexibility it gives - especially when working with writers. They can work entirely in the rule database, creating new triggers and variations, whole gameplay sequences and consequences, without waiting on code or level design support to script it for them.

# Answer
> 2 votes
If you want some procedurally generated dialog which should 1. vary and 2. keep the context in mind, you could write your dialog lines with placeholder tokens which are inserted at runtime:

> {{salutation}} {{playername}}. I heard we will have {{weather\_prognosis}} today. That makes me {{weather\_opinion}}.

Now *how* these tags are replaced at runtime is a matter of how complex you want to be in each individual case. There are several strategies which you could use:

1. Direct replacement. A token like `{{playername}}` is directly bound to the value of a game variable. This is the most trivial replacement strategy.
2. Randomness. Tokens which have a list of strings from which one is picked at random. `{{salutation}}` could use such a list with strings like "Hi", "Hello", "Good day" etc.
3. Context-sensitive replacement. Tokens like `{{weather_prognosis}}` check the state of your weather system to have the NPC says something appropriate. `{{weather_opinion}}` also takes personality variables of the current NPC into account.
4. Context-sensitive randomness. Combination of the previous two points. It might seem more natural if the `{{salutation}}` used by the NPC is not completely random. An NPC would use different salutations depending on how refined the NPCs manners are and how well they know the player-character, but they still wouldn't use the same salutation every time. To implement this, you could use weighted randomness and have the weight of each entry being dependent on the current state of various variables.

You could make this system even more powerful by allowing nested replacement tokens. The phrase above could be one entry of a list of phrases which are the replacement for the `{{generic_smalltalk}}` token.

The nice thing about this system is that you won't be forced to implement the full complexity from the start. You could start with a simple string-to-string replacement for most tokens to get the game to a playable state and then add more complex substitution rules for each token later.

A disadvantage of this system is that it makes translating a lot more difficult. Different languages have different rules for how relationships affect word choice and grammar (look at the convoluted rules for honorifics in Japanese, for examples). You and your primary writers won't be able to anticipate all these nuances. So translators might have to tweak the algorithms which pick appropriate responses or even add completely new tokens. That will require programming skills. But you will have that problem with any system which generates text procedurally.

# Answer
> 0 votes
I can see two options here :

* Probably the best in terms of results : Write each possible combination job/personality **by hand**. You have control on the output but it takes a lot a time and is not much fun. Furthermore it gets complicated if you want to add text in the future.
* Using a **template** such as @Philipp said is probably the easiest solution for you. You can add personality in those texts by varying the **punctuation** and **vocabulary**. For instance a depressive character would have sentences ended with '...' and his vocabulary would include adjectives like 'sad', 'depressing' etc. A happier character would have a lot of '!' and interjections such as 'Hey !' or 'Wow !'.

The NLG would be the coolest feature and really create new dialogues each time but I'm not sure if it's relevant for a demo. It would take much more time than making the game itself.

---
Tags: procedural-generation, python, npc, dialogue-tree
---


# Question
Title: What is an alternative to scratch damage to solve combat deadlocking?
Scratch damage is a game mechanic whereby any successful attack always does some minimal amount of damage. This is often used in subtractive combat systems, where the defense is subtracted directly from the damage done by an attacker. Therefore, the target will always take some minimal damage.

The downside of such a system, for me at least, is that it's a hack. It takes a simple formula like `Damage = Attack - Defense` and turns it into a (slightly) more complex one: `Damage = max(Attack - Defense, 1)`.

I also feel that it detracts from a player's skill in developing their character/etc. No matter how many defense bonuses they get, every attack will do some small damage. So why get your defense so high, if it won't mean anything?

Furthermore, this now encourages the use of larger numbers for Hp and damage, so that the scratch damage is truly negligable. After all, if the minimum damage is 1, and you only have 10 Hp, that's still 10% of your health. Even with 20 Hp, that's 5%. And I would rather avoid using larger numbers like that unless it's absolutely necessary.

However, there is one very important upside of scratch damage: it solves the deadlock problem.

Deadlock happens when neither side is able to do damage to the other. If you invest all of your resources into defense, and few into attack, then your character may not take damage, but they won't be able to *deal* very much either. Thus, you could come upon an encounter where neither side will be able to inflict damage, so battle continues forever. This is especially if you don't have random mechanics like critical hits (which I also hate).

At least with scratch damage, *someone* will eventually win. It may only be the one with the most Hp or highest number of attacks, but the battle will end.

So I like having a combat system where there will always be an outcome. But I don't like having scratch damage. What are my alternatives?

Alternatives that *don't* involve rolling random numbers; I want combat to be 100% deterministic. If the same battle is fought, the exact same outcome must happen.

If you want specifics on the gameplay, think in terms of turn-based combat, where battle can be automated (you design your forces, then pit them against others).

# Answer
You could implement a fatigue/stamina system. As more and more attacks are done the player becomes increasingly fatigued meaning they are unable to maintain such a good defense (that shield arm suddenly starts feeling really heavy after swinging the sword 50 times) as fatigue increases, defense falls. This means a player who has developed a good character won't take damage in quick encounters but longer drawn out combat will result in increasing damage preventing a deadlock.
> 42 votes

# Answer
This seems like a very open-ended question. Solutions (that aren't already mentioned) to prevent deadlocks:

* Allow for deadlocks as a viable end result. This is the least expected or typical solution. In an RTS game, for example, this might be an uneasy cease-fire, or tense but low-key conflict in a violent balance.
* A time limitation with ties allowable
* A time limitation wherein the first hit/score/point after the limit wins (sudden death/overtime)
* Random dangers in the system (a la bombs in Super Smash Bros). This changes the focus of the situation from offense to defense.
* Any external factor to imbalance the system (e.g. a third agent with high damage and low armor, an agreement by both sides to "duel" without all that armor)
* Defense as a % reduced (probably the simplest solution, as long as the defense is capped)
* Skills or tactics which alter the dynamics of gameplay (choices that don't result in damage, such as a Cloak/Invisibility skill)
* Means of doing much higher damage (classic critical hits, stealth bonuses, height bonuses, terrain bonuses, an ability that turns random portions of ground into lava)
* Means of damaging or lowering armor, or causing a damage directly targetted to high-defense characters (skill that inverses armor in the calculation, so agents with lower defense receive less damage)
* Limited use items or skills (e.g. bombs, powerful but draining abilities). Only useful if there are long-term goals beyond the deadlock with which to balance limited use
* End combat artificially (classic "Flee" option)
> 23 votes

# Answer
As variant, you may add wound accumulation. Surely, giant copper axe will not penetrate heavy steel armour, but it will do some blunt damage, and may even break bones. The same is true for bullets and vests.

Every time a character is hit, convert part of piercing and slashing damage into blunt damage, which accumulates. After certain threshold (that depends on endurance, for instance), the accumulated damage will interfere with the character's combat skills. Some options here:

* Armor could be less efficient when taking hits in the same body parts.
* Significant wounds: periodic damage, weakness due to pain.
* Severe wounds: short-term loss of consciousness (rendering the character very vulnerable).
* Extreme wounds: permanent stat loss (if character manages to survive).

Related: Damage mechanics in Dwarf Fortress
> 8 votes

# Answer
Implement different types of damage, with armors that only protect against some types of damage. For example, kinetic damage, acid damage, fire damage, etc. No armor should protect against each type of damage.

Users could layer their armors to protect against all damage types, but they couldn't protect against all damage types at the same time. This implements some strategy into battles as well, where players have to switch damage types to get through the various layers of armor.
> 6 votes

# Answer
Add a wear-down mechanic for defense. Make every attack slightly reduced the defense of the target.

Eventually even a weak attack will wear down the targets defense enough to inflict actual damage.
> 5 votes

# Answer
You could just *not* have a defence stat and just give bigger enemies bigger hp. I know you want to avoid gigantic numbers, but if you want a deterministic, turn based game where attacks aren't based on the players input directly (there is no chance of human error messing the attack up) the defence stat seems a little pointless as well.

If you are worried about the presentation aspect you could break HP down into Hearts or Health pips EG 100 hp = 1 heart. Hearts start to go black as a character loses HP, then disappear entirely. That way it's easier for the player to understand than 129301239103123hp, but you don't have to worry about balancing some magic equation.

If you are worried about realism, you could always have it animated to look like the attack's target successfully blocks or is only lightly scratched until the killing blow.
> 4 votes

# Answer
If you are OK with stepping out from the world of integers and willing to spice up subtraction system, you can use damage reduction algorithm from Warlords Battlecry III:

```
damage = attack

while DR > 0:
    usedDR = DR
    if DR > damage
        usedDR = damage
    damage = damage - usedDR * 0.5
    DR = (DR - usedDR) / 2

HP = HP - damage

```

This is the function that behaves very similar to the above pseudocode:

```
damage(attack, DR) = attack * 2 ^ -(DR/attack)

```

When DR is smaller than attack (incoming damage), it behaves like attack - k\*DR where k is 0.693 (`ln(2)` to be exact). When DR is close to or bigger then incoming damage than the damage is halved `DR/attack` times. For example for DR = 30 and attack = 10, damage would be 1.25 (attack halved 3 times).

It may look like more complicated and harder for human to evaluate but it is hack free and changes in both parameters are relevant. If attacker gains bonus attack power or defender gains or loses DR by even small amounts, the resulting damage will change.
> 3 votes

# Answer
**Use floats.**

Even if you present integer HP to the player, use float for hp and float for damage.

I am using fractional armor classes now, where armor of 1.0 is *invincible* and armor of 0.0 means "takes full damage". Damage is reduced as:

```
float hpReduction = hp - dmg*(1.f - armor) ;

```

This formula has the effect of allowing "double damage" by setting armor to -1.

I have classified damage into categories as well, see Starcraft's concussive/explosive damage types, or Eve's damage type system for an example.

So now, a little imp scratching at your .99 class armor *will eventually* Cherry Tap you to death, but the attacks will appear to do no damage to the player (he will remain at 1 hp as he goes from 1.15 hp to 1.1499 hp the next attack..)
> 1 votes

# Answer
A skill graph could put some damage-dealing skills as prerequisites for higher-level defensive skills to reduce a player's ability to make highly asymmetrical builds.

Critical hits can get some damage through as long as one's defense is not absurdly high. If you make them periodic rather than random, you still have deterministic combat.

After a number of failed hits, you might automatically reduce attack speed in favor of higher hit chance and damage. Your super-fast scratch character was doing ten attacks per second; now, after fifteen attacks doing no damage, it gets three attacks per second at +50% to hit and +200% damage. This is similar to critical hits, but it's faster for this sort of situation.

You could use percentage based damage reduction from armor, but to make it more interesting than another way to buff your maximum HP, you could have the reduction percentage be greater for weaker hits. For instance, 90% reduction for 1-20hp of damage, 60% for 20-30, and 30% for everything else.

Finally, don't worry about large numbers. They give you a much finer degree of control than small ones. Having a level 1 character start off with 100 hit points means you can have something that kills them off in seven hits but not five. It means you can have poison damage and other damage over time effects that aren't outrageously devastating (as well as some that are, if you like). If you don't like displaying large numbers, find a way not to display them.
> 0 votes

# Answer
You say you want there to always be a resolution, but does that have to be a victory?

Consider the approach used by *Dominions*--on turn 50 the attacker automatically routs. On turn 75 the defender automatically routs. (A rout doesn't automatically work--some units are immune to routing and even if an immobile unit routs it can't actually leave.) On turn 100 everything left is killed.

While I disagree with the exact way it functions (there are situations where it simply takes too long to kill the other side) the basic idea remains valid.

What I would suggest:

Look at some measure of the power of each side. (Hit points are an obvious starting point but be careful, *Dominions* has a problem in this regard where hit points "loss" that isn't meaningful is being counted--shapechanging, summons etc. resulting in armies routing due to casualties when they didn't even take any.) Keep track of the minimum value reached and note how many turns it has been since a new minimum has been set. If it goes too long without a new minimum being set you have a deadlock of some kind and the attacker should retreat.
> 0 votes

# Answer
An alternative I haven't seen yet is that as your armour value makes the attack negative you could add a little RNG for a true block:

```
const stratchDamage = 1;
var armour = 10;
var blockCount = 0;

function registerAttack (incomingAttack)
{
    var incomingDamage = incomingAttack - armour;

    // Nothing unusual, deal damage
    if( incomingDamage > 0 )
    {
        dealDamage(incomingDamage);
    }

    // Armour cancels out attack, deal scratch damage
    else if( incomingDamage == 0 )
    {
        dealDamage(scratchDamage);
    }

    // Armour over attack value, check if can block
    else
    {
        var trueBlockChance = armour - incomingDamage;

        // blockCount starts at 0, will always block first attack
        if( trueBlockChance  > blockCount )
        {
            // Can technically do nothing, or trigger block animations etc
            block();
            blockCount ++; // Increment block so they can't block forever
        }
        else
        {
            dealDamage(stratchDamage);
            blockCount = 0;
        }
    }
}

```

The higher the deficit of damage after armour is taken into account, the more attacks the character can block before taking another bout of scratch damage.

This provides a little extra scale for defensive stats whilst not making them invulnerable, also allows attacks to get through this block mechanic should you want them to and naturally will prevent deadlocks.

Fights might take a long time if you have stacked stats in your defence over offence, but it'll get there in the end.
> 0 votes

# Answer
Lots of 3D fighting games avoid scratch damage. Examples are Tekken and Soul Calibur 2. They avoid this by making it difficult to have a perfect defense. Some attacks are simply too fast to react to. I think it's a pretty good solution.
> -1 votes

# Answer
I think reducing the effectiveness of Defense is not a good option. Depowering a player leads to a bad game experience. Why not go the other way around?

Why not powering up the Attack as time goes by. This makes scratch damage increase with time, reducing the incentive of blocking. In mid-late game, a character can kill another while wailing on him while he's defending.

Some pnp rpgs implement a "tension mechanism". Each turn tension increases by one. All the rolls have the added modifier of the tension value, pushing the battle towards an end.

Another idea, coming from Fighting games, is an attack that goes through defense. I don't know if your game is turn based or real-time, but this attack could also open the opponent to a combo or disable him or some of his abilities temporarily.

I believe the trick is not to undepower defense. Make other options just as good as defense, or reduce the times where defense is a good option.
> -1 votes

---
Tags: game-design
---