# Question
Title: Balancing stats in a monster fighting game (similar to Pokemon battle/stats)
I'm trying to create a game that uses a battle and monster system like Pokemon. I'm using some similar equations that I've modified to fit my desired level/tier system. One thing I'm trying to figure out is how to balance my monsters when I am creating them. I will have stats for health, attack, defense, special attack, special defense, and possibly speed. Unlike Pokemon, I'd like to have all my monsters be relatively balanced so that at high levels you could conceivably use any one.

One thought I had was to write a simple program that allowed me to create a monster. Its stats would start at a base 50 and every time I increased its stat by 4, the other stats would drop by 1. I could then tailor my monsters to be defense heavy while lacking offense, etc. One issues, is that my health equation yields a higher amount of health per increase in stat point versus the other stats.

Do you have any suggestions for improvements or a new system.

# Answer
Slightly off topic, but I saw this video recently.

This is mostly only an issue in multiplayer games, but if things are balanced completely? There will only be a few ways in which you can play it.
> 3 votes

# Answer
What you could do is simply leave health out of the stat equations and keep it at 50. The other stats would account for higher level battles, like if you're defensive then you won't get hurt as much when attacked, when you're offensive then you give more damage and the opponent loses more health.
> 3 votes

# Answer
Balance is pretty meaningless if one doesn't understand how the numbers interact. Your proposed solution, or even TMP's both assume that the 'value' of your stats are all closely related. The reality is that, depending on the underlying mathematics that govern your system, they could very well be far out of sync.

A good example of this is the '+3' cycle from the first release of Magic: the Gathering. There was one card of each color that did 3 of something. And in the noble MtG tradition, the blue one was so ridiculously overpowered that it blew the others out of the water. The value of '3' for the blue card was way WAY more than the value of the '3' on the other cards. The same could be true for your monster stats.

Balance isn't just a switch that you can flip. It's a complicated and nuanced process that goes directly to the heart of your game. The only way to even begin to make some kind of auto-balancing system is to generate a simple genetic AI that can play your game (or a simulation of it) and look at it's play to try to find degenerate strategies.
> 2 votes

# Answer
You mentioned pokemon game, therefore I'll assume you want to include skills for your monsters.

---

I'd say your main problem would not be stats, but rather skills (as far as I can remember Pokemons ;)). Your problem has a bit different category than, let's say, RTS games face. In most of RTS games units don't usually have skills (or if they do, like in Starcraft, they serve particular situation(s), but not general case) and it's easier to evaluate their overall value\* and design stats - even concerning leveling possibilities.

But onto your case. Let's imagine situation in which you possess two different Pokemons A and B (stats described relative to each other):

* pokemon A has less HP, little more attack, little less defense, attack debuff skill;
* pokemon B has more HP, less attack, little more defense, no skills at all

From stats point of view, Pokemon B is more valuable as defensive one. If you design Pokemon B to acquire slightly more defense and HP with each level than Pokemon A does, you can notice how his value increases with each level even further. **But**, take into consideration how this one attack debuff skill can affect battle result. If this skill's power rises with each level then it becomes less clear which of these two is more valuable **in general**. Going even further, you can use Pokemon A for weakening opponent's Pokemon-with-powerful-attack-and-powerful-attack-skills, take as much damage as he can handle (assuming Pokemons' skills are restricted in use count) and then use Pokemon B to finish him or even use other offensive Pokemon C. Considering greater effects of one Pokemon type on other Pokemon type - possibilities are endless.

Conclusion is: you should not concentrate purely on Pokemon stats, but on overall mix of fighting/defensive/put-what-you-need-here stats **including skills**. In your case, skills are probably most vital for gameplay, thus making your task even more difficult. My advice is not to concentrate on balancing stats in early/late game, but make them **unique** in terms of stats **and skills**. Diversity is what makes your units more attractive to their owners and serves well the purpose of putting greater challenge to the player.

* value does not mean costs, but overall usefulness of this unit
> 1 votes

# Answer
In games I've designed I sometimes assign a value to different stats. Perhaps Damage is more valuable than Speed and Health is a higher number than other stats, so if your base number is 50 Damage, 50 Speed and 500 Health, I might say for every 2 points of Damage changed would equal 3 Speed or 40 Health. Could turn out like 56 Damage, 50 Speed and 380 Health or 40 Damage, 59 Speed and 580 Health. When I have made games I've noticed some things are just more valuable than others and a consistent change across the board unbalances things.
> 0 votes

---
Tags: rpg, balance
---


title: How to render text on an 3d Object?

text:
# Question
Title: How to render text on an 3d Object?
I want to render text on an 3d object. I'm trying to simulate a digital signage LED panel.

My lcd Panel has a material and a texture.

How can I do ?

Using 3d Text ?

Thanks

# Answer
> -1 votes
Solved: using TextMesh component !

---
Tags: unity, text
---


# Question
Title: A coroutine to rotate one point around another by a given angle without referring to game object
I need to rotate a point around another point (in 2D) by a given angle over a given duration, independent of game object (meaning that I've manually created the points and they're not positions from a game objects transform ) as shown in the image below where point `B` rotates to `C` by and angle `e` around `A` by with radius `AB`. Using a coroutine would be preferable.

**UPDATE**

Based on links provided by @MichaelHouse I wrote the following methods to rotate a control point over time by a certain angle but it rather moves to a point (which is not the desired point) immediately to another point, not by the right angle. I'm not sure what I've done wrong.

```
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle)
{
    return angle * (point - pivot) + pivot;
}

IEnumerator RotateControlPointWithDuration(Vector3 point, Vector3 pivot, float duration, float angle)  {
    float currentTime = 0.0f;
    float ourTimeDelta = 0;

    ourTimeDelta = Time.deltaTime;
    float angleDelta = angle / duration; //how many degress to rotate in one second

    while (currentTime < duration)
    {
        currentTime += Time.deltaTime;
        ourTimeDelta = Time.deltaTime;

        Vector3 newPos = RotatePointAroundPivot(point, pivot, Quaternion.Euler(0, 0, angleDelta * ourTimeDelta));
        points[0] = new Vector2(newPos.x, newPos.y);

        yield return null;
    }
}

IEnumerator runMovement()  {

    yield return new WaitForSeconds(2.0f);
    Vector3 point = new Vector3(points[0].x, points[0].y, 0);
    Vector3 pivot = new Vector3(points[3].x, points[3].y, 0);
    StartCoroutine(RotateControlPointWithDuration(point, pivot, 2.0f, 45.0f));
}

```

**UPDATE 2**

I've tried another approach using trig functions, but the point moves erratically before finally arriving at a point that seems to be the right point. Please see the code below:

```
 IEnumerator runMovement()  {

    yield return new WaitForSeconds(2.0f);
    Vector2 pivot = points[3];

    StartCoroutine(RotateControlPointWithDuration(pivot, 2.0f, 90.0f));

}

   IEnumerator RotateControlPointWithDuration(Vector2 pivot, float duration, float angle)
{
    float currentTime = 0.0f;
    float ourTimeDelta = 0;
    Vector2 startPos = points[0];

    ourTimeDelta = Time.deltaTime;
    float angleDelta = angle / duration; //how many degress to rotate in one second

    while (currentTime < duration)
    {
        currentTime += Time.deltaTime;
        ourTimeDelta = Time.deltaTime;

        points[0] = new Vector2(Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) - Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.x,
                                                        Mathf.Sin(angleDelta * ourTimeDelta) * (startPos.x - pivot.x) + Mathf.Cos(angleDelta * ourTimeDelta) * (startPos.y - pivot.y) + pivot.y);

        yield return null;
    }
}

```

# Answer
> 1 votes
Your first "Update" code is mostly right, but it's using the wrong time delta.

Since "delta" just means difference, we shouldn't automatically reach for any old time variable with "delta" in the name, but instead consider which two endpoints we want a difference *between*.

Here the delta taken by the quaternion constructor wants the time difference between now and the start of the animation, so it can construct a rotation accounting for the full arc that should have been traversed over that interval. But Time.deltaTime gives you the difference between this frame and the previous frame - this will always hover close to your framerate (eg. 33 or 17 ms), rather than progressing smoothly from zero to your full duration.

So, we can correct and simplify the code a bit like this:

```
IEnumerator RotatePointAroundPivot(Vector3 pivot, float angle, float duration) {

    Vector3 startPoint = points[0];

    float progress = 0f;
    float rate = 1f/duration;

    while(progress < 1f) {
        progress += Time.deltaTime * rate;
        Quaternion rotation = Quaternion.Euler(0f, 0f, angle * Mathf.Min(progress, 1f))

        // If your output is a Vector2, this will implicitly omit the z.
        points[0] = pivot + (rotation * (startPoint - pivot));

        yield return null;
    }
}

```

Now we have a `progress` variable that increases from zero to one over our duration, and we can use this to blend the angle from zero up to the full desired arc.

# Answer
> 1 votes
First of all, you need a couple of things. You need to store the angle you want to rotate the object by, the time it should take and the point you want to rotate it around obviously, but you'll also need to store when you started the rotation relative to a fixed point in time (e.g. the epoch, resource here).

Inside the coroutine you'll need the current time relative to the same point in time as before. Subtract the time you started from it and divide it by the time the rotation should last. This gives you a value between 0 and 1 that tells you how far you are currently. It's 0 when it begins, 1 when it ends, 0.5 when it's halfway there, etc. I'll call this `t`.

Based on `t` you can get the angle you need to rotate B relative to the original position by just multiplying it with it. The only thing left to do is to actually rotate the vector. Refer to the first part of this StackOverflow question if needed (This is a pretty useful formula, so try memorizing it).

So, to rotate the B vector around A, subtract A from B, rotate the resulting vector by the current angle and add A back to it.

So, in code

```
// Inside the coroutine
float t = (currentTime - startTime) / duration;
float angle = totalRotation * t;

// If the angle is in degrees, then convert it to radians by multiplying
// by Mathf.Deg2Rad
// A positive angle creates a counter-clockwise rotation

Vector2 ab = B - A;
Vector2 rotated = new Vector2(
    ab.x * Math.cos(angle) - ab.y * Math.sin(angle),
    ab.x * Math.sin(angle) + ab.y * Math.cos(angle)
);

return A + rotated;

```

---
Tags: unity
---


title: Getting scene normals in Unity

text:
# Question
Title: Getting scene normals in Unity
When I get the depthnormals with the shaderreplace script, it just replaces all the shaders in the scene and uses the meshes geometry to calculate the normals, ignoring the normalmap textures applied on them.

How can I get the final rendered scene normals to a rendertexture like it appears in the editor windows normal debug mode that is used for deferred light calculations and ambient occlusion and such ?

# Answer
you can use Replacement Shader to Displaying Mesh Normals

First attach this script to camera:

```
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ReplacementShaderEffect : MonoBehaviour
{
    public Shader ReplacementShader;

    void OnEnable()
    {
        if (ReplacementShader != null)
            GetComponent<Camera>().SetReplacementShader(ReplacementShader, "");
    }

    void OnDisable()
    {
        GetComponent<Camera>().ResetReplacementShader();
    }
}

```

then use this shader in above script for Replacing shaders

```
Shader "Tutorial/Display Normals" {
    SubShader {
        Pass {
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    #include "UnityCG.cginc"

    struct v2f {
        float4 pos : SV_POSITION;
        float3 color : COLOR0;
    };

    v2f vert (appdata_base v)
    {
        v2f o;
        o.pos = UnityObjectToClipPos (v.vertex);
        o.color = v.normal * 0.5 + 0.5;
        return o;
    }

    half4 frag (v2f i) : COLOR
    {
        return half4 (i.color, 1);
    }
    ENDCG

        }
    }
    Fallback "VertexLit"
    }

```

In your comments you mentioned that you need store result to Rendertexture and use it in shader for post-processing

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

public class CaptureMe : MonoBehaviour {
    public RenderTexture RT;
    public Camera SecondCamera;//Second Camera Renders Normal that store to RenderTexture
    public Shader shader;//shader that you want pass result to it

    void Update(){
    }

    void OnRenderImage(RenderTexture source,RenderTexture target){

        int resWidth = Screen.width;
        int resHeight = Screen.height;

        RT = new RenderTexture(resWidth, resHeight, 24);
        SecondCamera.targetTexture = RT; //Create new renderTexture and assign to camera
        Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); //Create new texture

        SecondCamera.Render();

        RenderTexture.active = RT;
        screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0); //Apply pixels from camera onto Texture2D

        SecondCamera.targetTexture = null;
        RenderTexture.active = null; //Clean

        Material mat = new Material(shader);

        mat.SetTexture ("_NormalScene", RT);

        Graphics.Blit (source, target,mat);

        Destroy(RT); //Free memory

    }
}

```

---

# Update

If you need better result you should be calculating the world normals.

```
Shader "Tutorial/DisplayNormal2"
{
    SubShader

    {
        Tags { "RenderType" = "Opaque" }
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct v2f

            {
                float4 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;

            };
            v2f vert(appdata_base v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv.xyz = UnityObjectToWorldNormal(v.normal);
                return o;
            }
            fixed4 frag (v2f i) : SV_Target
            {
                float3 c = i.uv.xyz;
                return float4(c, 1);
            }
            ENDCG
        }
    }
}

```
> 2 votes

# Answer
I'm assuming you're talking about the gbuffers of the deferred rendering path

According to this tutorial.

You need to declare the samplers in your shaders:

```
sampler2D _CameraGBufferTexture0;
sampler2D _CameraGBufferTexture1;
sampler2D _CameraGBufferTexture2;

```

Then you can read from them like so

```
float3 albedo = tex2D(_CameraGBufferTexture0, uv).rgb;
float3 specularTint = tex2D(_CameraGBufferTexture1, uv).rgb;
float3 smoothness = tex2D(_CameraGBufferTexture1, uv).a;
float3 normal = tex2D(_CameraGBufferTexture2, uv).rgb * 2 - 1;

```

You're interested in `_CameraGBufferTexture2`
> 1 votes

---
Tags: unity, shaders, graphics, normals
---


# Question
Title: How to move a sprite quickly whilst animating it?
At the moment I am creating a program in Python, and Pygame, similar to Fire emblem, so a game that has a tile based system in which the sprites use to move to and determine location. I have been able to code the movement of the sprites to a tile, however, as the sprite is being animated whilst moving, using pauses in the code to give the illusion that it is one sprite changing stance, it means that the whole program waits around half a second before continuing on meaning that the movement is very slow (This is shown through the Trans\_1 = 0.5 and Trans\_2 = 0.15 variables). I was wondering if anyone could help me in finding a way to run the animation, with the pauses in, whilst moving the sprite from one position to another.

Here is the code I have for it, sorry if it's a little long:

```
import pygame as pg, sys
from pygame.locals import *
import shelve
import time

pg.init()
GREY = ( 50, 50, 50)
WHITE = (255,255,255)
DARK_GREEN = ( 0 ,100, 0 )

#Defining the Display surface
x = 750 #The x value represents the x value of the resolution.
y = 609 #The y value represents the y value of the resolution.
HW,HH = x/2,y/2#Finding the Middle of the screen
clock = pg.time.Clock()

Screen = pg.display.set_mode((x, y))
pg.display.update

def Tile_Round(x, y,x50 = 0,y47 = 0):
    x50 = 0
    y47 = 0
    while x >= 50 or y >= 47:
        if x >= 50:
            x -= 50
            x50 += 1
            print(x,x50)
        elif y >= 47:
            y -= 47
            y47 += 1
            print(y,y47)
    N_xPos = 50*x50
    N_yPos = 47*y47
    return N_xPos, N_yPos

class Soldier_Ally(pg.sprite.Sprite):

    def __init__(self, S1_xPos,S1_yPos):
        ld = pg.image.load
        self.S1_xPos = S1_xPos
        self.S1_yPos = S1_yPos
        self.SS1_Img = ld("Soldier_Standing_1.PNG").convert_alpha()
        self.SS2_Img = ld("Soldier_Standing_2.PNG").convert_alpha()
        self.SS3_Img = ld("Soldier_Standing_3.PNG").convert_alpha()
        self.SU1_Img = ld("Soldier_Up_1.PNG").convert_alpha()
        self.SU2_Img = ld("Soldier_Up_2.PNG").convert_alpha()
        self.SU3_Img = ld("Soldier_Up_3.PNG").convert_alpha()
        self.SU4_Img = ld("Soldier_Up_4.PNG").convert_alpha()
        self.SD1_Img = ld("Soldier_Down_1.PNG").convert_alpha()
        self.SD2_Img = ld("Soldier_Down_2.PNG").convert_alpha()
        self.SD3_Img = ld("Soldier_Down_3.PNG").convert_alpha()
        self.SD4_Img = ld("Soldier_Down_4.PNG").convert_alpha()
        self.SL1_Img = ld("Soldier_Left_1.PNG").convert_alpha()
        self.SL2_Img = ld("Soldier_Left_2.PNG").convert_alpha()
        self.SL3_Img = ld("Soldier_Left_3.PNG").convert_alpha()
        self.SR1_Img = ld("Soldier_Right_1.PNG").convert_alpha()
        self.SR2_Img = ld("Soldier_Right_2.PNG").convert_alpha()
        self.SR3_Img = ld("Soldier_Right_3.PNG").convert_alpha()
        self.SR4_Img = ld("Soldier_Right_4.PNG").convert_alpha()

        self.Img_Size = self.SS2_Img.get_size()
        self.Img_Rect_Size = self.SS3_Img.get_rect()
        self.Size = (50,47)

    def Draw_SR(self,N_xPos):
        Trans_1 = 0.5
        Trans_2 = 0.15
        N_xPos = N_xPos
        Stage_Img = pg.image.load("Stage.PNG").convert()
        for x in range (0,10):
            self.S1 = Screen.blit(self.SR1_Img,((self.S1_xPos,self.S1_yPos)))
            self.S1_xPos = (self.S1_xPos + (N_xPos/29))
            print(self.S1_xPos)
            pg.display.update()
            time.sleep(Trans_1)
            Screen.blit(Stage_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size)))
            pg.display.update()
            self.S1 = Screen.blit(self.SR2_Img,((self.S1_xPos,self.S1_yPos)))
            pg.display.update()
            time.sleep(Trans_2)
            Screen.blit(Stage_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size)))
            self.S1 = Screen.blit(self.SR3_Img,((self.S1_xPos,self.S1_yPos)))
            self.S1_xPos = (self.S1_xPos + (N_xPos/29)) #1
            print(self.S1_xPos)
            pg.display.update()
            time.sleep(Trans_2)
            Screen.blit(Stage_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size)))
            self.S1 = Screen.blit(self.SR4_Img,((self.S1_xPos,self.S1_yPos)))
            pg.display.update()
            time.sleep(Trans_1)
            Screen.blit(Stage_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size)))
            self.S1 = Screen.blit(self.SR3_Img,((self.S1_xPos,self.S1_yPos)))
            self.S1_xPos = (self.S1_xPos + (N_xPos/29))
            print(self.S1_xPos)
            pg.display.update()
            time.sleep(Trans_2)
            Screen.blit(self.SR2_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size)))
            self.S1 = Screen.blit(self.SR2_Img,((self.S1_xPos,self.S1_yPos)))
            pg.display.update()
            time.sleep(Trans_2)
            Screen.blit(self.SR2_Img,((self.S1_xPos,self.S1_yPos)), pg.Rect((self.S1_xPos,self.S1_yPos),(self.Size))) #2

    def Game_Start():
        S1_xPos = 0 #Soldier1_x_Position
        S1_yPos = 0 #Soldier1_y_Position
        Screen.fill(GREY)
        Stage_Img = pg.image.load("Stage.PNG").convert()
        Stage = Screen.blit(Stage_Img,(0,0))

        x = 0
        y = 0
        Table_Loop = True
        pg.draw.line(Screen, WHITE, (0, y), (750, y), (1))
        pg.draw.line(Screen, WHITE, (x, 0), (x, 609), (1))
        pg.display.update()
        while Table_Loop == True and x <= 750:
            x+=50
            y+=47
            pg.draw.line(Screen, WHITE, (0, y), (750, y), (1))
            pg.draw.line(Screen, WHITE, (x, 0), (x, 609), (1))
            pg.display.update()

        def Sprites_Standing(S1_xPos,S1_yPos):
            Selected = 0
            Sprite_Loop = True
            while Sprite_Loop == True:
                S = Soldier_Ally(S1_xPos,S1_yPos)
                S.Draw_SS()
                for event in pg.event.get():
                    if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
                        Mouse_x,Mouse_y = pg.mouse.get_pos()
                        if S.S1.collidepoint(Mouse_x,Mouse_y):
                            Selected = 1
                        elif Selected == 1:
                            N_xPos,N_yPos=Tile_Round(Mouse_x,Mouse_y)
                            First = 1
                            print(N_xPos,N_yPos)
                            Sprite_Loop = False
                        else:
                            pass

            if N_xPos > S.S1_xPos:
                S.Draw_SR(N_xPos)
                Sprites_Standing(S.S1_xPos,S.S1_yPos)

        Sprites_Standing(S1_xPos,S1_yPos)
        pg.display.update()

    if __name__ == "__main__":
        Initial_Time = (time.time())
        pg.display.set_caption('Fortress')
        Buttons()
        Menu_Active()

```

# Answer
So I think you're looking for an animation system. You'll want to keep ticking the game forwards (never sleep in the game loop) while changing the sprite frame every now an then. Here's an example of a very basic animation system: (pseudo-Python)

```
class Animation:
    def __init__(self, frames, frame_interval):
        self.frames = frames
        self.frame_interval = frame_interval
        self.frame = 0
        self.currentFrame = 0
        redrawSurface()

    def tick(self):
        self.frame += 1
        if (self.frame >= self.frame_interval):
            self.current_frame = (self.currentFrame + 1) % len(self.frames)
            redrawSurface()

    def redrawSurface():
        current_frame = self.frames[self.current_frame]
        self.surface = pygame.Surface((current_frame.w, current_frame.h))
        # Draw a part of a surface to another.
        self.surface.blit(PLAYER_SPRITE, current_frame)

```

So you'd supply the animation frames to the animation, and you'd call `tick` from your game loop, which would periodically change the surface every now and then. Then you just need to use the animation's surface to draw your player. So something like this:

```
while True:
    ...
    player.animation.tick()
    player.position += player.speed
    screen.blit(player.animation.surface, player.position)
    ...

```

All in all, the use of sleep is a beginner "mistake" in game dev. It's crucial to keep the game loop running without interuptions for smooth movement as you've noticed. It might be a good idea to lookup a tutorial on basic game loops & animations, I'm sure you can find some.

Note that there might be some pygame specific animation stuff that you could use instead of rolling your own, but I'm not really that familiar with the pygame functionality these days anymore.
> 1 votes

# Answer
Here's how to make a very simple animation system in Pygame.

* Add all your frames in a list, called, for example, `frames`.
* Let `frame_duration` be however many milliseconds you want each frame to last.
* Let `current_frame` track which frame you're on.
* Let `last_anim_update` track the last time the current frame was incremented.
* In your `update()` method, continuously check to see if the `current_time - last_anim_update > frame_duration`. When it is, increment the current frame.

Then you can set things up like this:

```
idle_frames = [frame1, frame2, frame3]
frame_duration = 0.2
last_anim_update = 0
current_frame = 0

def update():
    ...
    if Globals.current_time - last_anim_update > frame_duration:
        current_frame += 1
        current_frame = current_frame % len(idle_frames)
        sprite = frames[current_frame]
        last_anim_update = Globals.current_time

def draw():
    # code which draws your sprite at the appropriate location

```
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Architecture for defining large numbers of meshes at runtime
In my project, there are large numbers (think 4-digit numbers) of 3D meshes that are created or modified one by one, or in groups, at runtime (based upon user interaction). These meshes have the following properties:

* They are rather "simple" (usually comprising less than 20, or even 10, triangles).
* Barely any two meshes will be exactly the same, as their geometry (e.g. location and number of vertices) varies based upon their environment/the location of other meshes in ways that cannot be described as a general geometric transformation (such as scaling).
* The concrete shape of the meshes adheres to a general "pattern" (for instance, all meshes range from a "start point" at (0, 0, 0) to an end point at (0, 0, length)), although the concrete shape will be determined per mesh (based upon an external configuration, or supplied by plugin code, etc.).
* The meshes will be oriented in different ways in the scene. The code that generates the meshes does not need to know about this, though.

**All of these are no problems as such.** The straightforward way I had thought of was to create a `GameObject` for each mesh, with a `MonoBehaviour` subclass attached that generates vertices, normals, and so on for the `Mesh` object of a `MeshFilter` component. The `Transform` of each `GameObject` can then conveniently be set according to the desired orientation of the mesh.

However, I have read various worrying reports that Unity does not cope well with large numbers of `GameObject` instances in the scene. For instance:

Based upon these resources, I figure I have various ways to proceed (that are not mutually exclusive):

* I continue as described above, but do not activate all the `GameObject` instances with my meshes, so they only serve as mesh geometry containers that a transformation can be applied to. **This sounds actually exactly like what I want (my objects do not need any self-controlled behavior), but a brief test indicates disabling actually shuts down drawing of the object, as well. As my players might zoom out far enough to see all objects at a time, this does not really solve my issue.**
* I do not store my meshes as individual `GameObject` instances with meshes, but I combine several of them into one large mesh. **I think it's well feasible to group a few hundred meshes and combine their geometry into a single `Mesh` object. I'd lose the individual `GameObject` `Transform` features, but I could of course apply the appropriate transformation on all the vectors returned for any given object myself. The possible issue I'm seeing here is that if one of my objects changes, I may have to recreate all the vertex, normal, color, etc. arrays for the entire chunk of hundreds of objects.**
* I figure out which meshes are actually visible at any given time, and only generate `GameObject` instances for these meshes. **Well, my objects are going to be spread across a map, and one will be able to see at least a very simple (outline) version of each of them when zooming all the way out. I might then create a combined low-res version of those objects that are farther away, but ultimately, this leaves me with the same issues as above, with the combined mesh.**

Thus, my question is: **Is using chunks of combined meshes (as one actual `Mesh` object per chunk, possibly split into several sub-meshes to support different textures) a viable way to go in my situation, despite the outlined issues with updating individual "inner" meshes?**

# Answer
You may want to take a look at Graphics.DrawMesh. It lets you draw individual meshes without individual GameObjects.
> 3 votes

---
Tags: unity, 3d-meshes
---


# Question
Title: Unity 3D: how to hide/unhide objects as player collides with them without flickering?
I have a maze grid of cubes that my player navigates through. I'm trying to make it so that each cube is only visible when the player is near it (so the player can only see the 4 cubes immediately around them at any one time).

I've been trying to do this using OnCollisionEnter/Exit, and turning on/off the renderer in each cube when the player is nearby (with colliders large enough that in theory the player should be touching more than one at a time). But this just creates a flicker effect.

I've also tried doing it using OnTrigger but that's not working because I need the cubes to be solid objects the player cannot pass through.

If anyone has some ideas, that'd be awesome. I've been trying to crack this one for a while but I'm a researcher rather than a coder so my programming skills are limited.

Thanks!

# Answer
Assuming the flicker is just because the visibility is changing too fast, you could smooth over the flicker by making the cubes fade in and out slowly over time.

You could have them start fading in, if they aren’t already fading in inside `OnCollisionEnter` and fade out if they aren’t already fading out inside `OnCollisionExit`.
> 2 votes

# Answer
If your blocks are in a grid, then it should be easy enough to do it without worrying about physics.

That said, if you do want to do it with physics, I would recommend using two colliders. The first is the cube itself, then there is a child game object which has a larger one which is marked as a trigger. Use OnTriggerEnter/Exit in a MonoBehaviour on the child GameObject to show/hide the parent's mesh.

Now, if you want to do it using a multidimensional array instead, that could be a bit more precise about having exactly the walls you want to be visible.

This example will put all of the code in a player class. It will also make a few assumptions about the cubes.

Assumption 1: All cubes are tagged with a special "wall" tag.

Assumption 2: All cubes are at integer positions and are of unit size (1x1x1). For example, a cube could be located at 1,1, but not at 1.5,1. If this is not the case, then some adjustments will need to be made to find all the cubes and put them in the right places in the array.

Assumption 3: the cubes are on the X-Y plane. If they are on the X-Z plane, minor adjustments will be needed.

Assumption 4: The size of the grid is not too big. A 100x100 grid is a 10,000 element array. Keep this in mind.

Some of these assumptions are to make it easier to find the cubes when the game starts. It is also possible to do this at design time, but it's a bit more work.

First, you'll need to keep track of all of the cubes in an array.

```
public class Player {
  MeshRenderer[,] grid;
  Vector2 minPos;
  int gridW, gridH;

  void Start() {
    GameObject[] walls = FindObjectsWithTag("wall");

    Bounds b = new Bounds(walls[0].transform.position, Vector3.zero);
    foreach (var wall in walls) {
      b.Encapsulate(wall.transform.position);
    }

    Vector2 size = b.size;
    minPos = b.min;
    gridW = (int)size.x;
    gridH = (int)size.y;
    grid = new MeshRenderer[gridW, gridH];

    foreach (var wall in walls) {
      Vector2 pos = wall.transform.position - minPos;
      var renderer = wall.GetComponent<MeshRenderer>();
      renderer.enabled = false;
      grid[(int)pos.x, (int)pos.y] = renderer;
   }
 }

```

}

So far so good. The grid is populated with cubes. It is basically a representation of your maze in code. If we wanted to, we could write a solver now. But that's not what we're here for. Now we just need to turn on the cubes near the player whenever they move and turn off the old ones. We should keep track of the old and new grid positions of the player so we can turn off old cubes and turn on the new ones without iterating through the whole grid.

```
int oldX = int.MinValue;
int oldY = int.MinValue;

void Update() {
  Vector2 pos = transform.position - minPos;
  int x = Mathf.RoundToInt(pos.x);
  int y = Mathf.RoundToInt(pos.y);
  if (oldX != x || oldY != y) {
    SetCubesEnabled(oldX, oldY, false);
    SetCubesEnabled(x, y, true);
    oldX = x;
    oldY = y;
  }
}

void SetCubesEnabled(int x, int y, bool enable) {
  SetCubeEnabled(x-1,y,enabled);
  SetCubeEnabled(x,y-1,enabled);
  SetCubeEnabled(x+1,y,enabled);
  SetCubeEnabled(x,y+1,enabled);
}

void SetCubeEnabled(int x, int y, bool enable) {
  if (x >= 0 && x < gridW && y >= 0 && y < gridH && grid[x,y] != null) {
    grid[x,y].enabled = enable;
  }
}

```

This should be sufficient to do the basics of what you want without relying on the physics system. Although relying on the physics system is a viable option as well, as I outlined above.
> 2 votes

---
Tags: unity, c#, game-design, game-mechanics
---


# Question
Title: Game object appears to accelerate too slowly
thank you for checking out my issue! I am trying to develop a game in java, but I have run into a problem. I would like to keep the physics as realistic as possible, so I am using a fixed time-step and 2D vectors to apply the force of gravity to a square. However, when I run the game it appears that the square is accelerating way to slowly. It could be that my physics concepts are flawed but I am pretty positive that my vector math is accurate, so I am having trouble finding the root of the problem. Hopefully I am not completely crazy and simply wasting your time, all help is very much appreciated.

Here is the main game loop:

```
private static void startLoops() {
    double targetFPS = 60.0;
    double targetUpdates = 60.0;

    //  accumulators for update/render
    double updateTime = 0.0;
    double renderTime = 0.0;

    //  variable to compare to accumulated cycle time
    //  desired time between updates in nanoseconds
    double targetDelta = 1000000000/targetUpdates;
    // desired time between frames in nanoseconds
    double targetFrame = 1000000000/targetFPS;

    // start time of the cycle
    double startTime = System.nanoTime();

    int updCount = 0;
    int frameCount = 0;
    double lastTime = System.nanoTime();

    while(shouldRun) {
        double curTime = System.nanoTime();
        //  end time of the previous cycle
        double cycleTime = curTime - startTime;
        startTime = curTime;

        updateTime += cycleTime;
        renderTime += cycleTime;

        //  input is checked every cycle
        cWrangler.updateInput();

        //  starts updating if enough time has passed
        //  while loop in case 2 full time-steps are accumulated
        while (updateTime > targetDelta) {
            double deltaTime = 1.0/60.0;

            //  do any updating here
            cWrangler.update(deltaTime);

            updCount++;

            updateTime -= targetDelta;
        }

        //  starts rendering if enough time has passed
        while (renderTime > targetFrame) {
            //  do any rendering here
            cWrangler.render();

            frameCount++;
            renderTime -= targetFrame;
        }

        if(curTime - lastTime >= 1000000000) {
            System.out.println("Frames: " + frameCount + ", Updates: " + updCount);
            lastTime = curTime;
            frameCount = 0;
            updCount = 0;
        }
    }
}

```

Please let me know if this question has been asked elsewhere. I am having trouble searching for a solution to my problem because I can't figure out the cause. Also, feel free to direct me to any resources you my think are helpful. Thanks again for taking some time to read through this!

# Answer
I think there’s a problem in this part:

```
    double curTime = System.nanoTime();
    //  end time of the previous cycle
    double cycleTime = curTime - startTime;
    startTime = curTime;

    updateTime += cycleTime;
    renderTime += cycleTime;

```

It looks like you are measuring the time the previous cycle took, then allowing both updates and rendering to each take that long. That would result in the time allowed doubling each time through the loop. Which seems like it would cause your reported symptom of too few updates.
> 1 votes

---
Tags: physics, movement, game-loop
---


# Question
Title: Rotate A towards B with limited turn rate
I want to rotate A towards B with a fixed turn rate per second. My math skills are very limited and I have no clue in how to accomplish this.

Best Regards

# Answer
> 1 votes
You could make use of linear interpolations, they give you a point between point A and point B, by a given normalized time **t** (between 0 and 1). Since they are linear, it will be made on a fixed rate.

The given example is with **Unity**, but the same maths are applied anywhere. Lets say I want to interpolate between Vector A and Vector B on 'x' seconds, I need a normalized reference to pass, so what we can make is to have a t value beginning at 0, and add it the value of the last frame's duration, divided by the duration of the interpolation. So, if without the division, t would reach 1 in a second, divided by the given duration will make t reach 1 on the given x seconds.

```
public Transform target;
public float duration;

void Update()
{
    if(Input.GetKey(KeyCode.Space)) StartCoroutine(Rotate(target.position - transform.position), duration);
}

IEnumerator Rotate(Vector3 direction, float s)
{
    Quaternion originalRotation = transform.rotation;
    Quaternion destinyRotation = Quaternion.Euler(direction);
    float n = 0.0f;

    while(n < 1.0f)
    {
        transform.rotation = Quaternion.Lerp(originalRotation, destinyRotation, t);
        t += (Time.deltaTime / s);
        yield return null;
    }
}

```

The interpolation's formula is very simple, if you want to make interpolations of other types of data (Vector, Color, Doubles, etc.) make sure those data types can have '-, +, and multiplication' operators applied upon each other. The given example is with a float, but the algorithm is the same for any data type:

```
/// Make sure to pass a t between 0 and 1, or you can internally clamp t inside this function.
public float Lerp(float a, float b, float t)
{
    return a + ((b - a) * t);
}

```

Hope it helps.

# Answer
> 1 votes
First code your AngleTo function:

```
    public static float AngleTo(float x1, float y1, float x2, float y2)
    {
        return (float)Math.Atan2(y1 - y2, x1 - x2);
    }

```

Start with your UnitPosition and derive NewAngle from the PositionToFace.

```
// Note: This may be backwards, in which case swap the arguments
// Note: This angle may be off by some constant, such as Math.Pi/4;
NewAngle = AngleTo(
               UnitPosition.x, UnitPosition.Y,
               PositionToFace.x, PositionToFace.y);

```

Now, during each update, add TurningRate to your UnitFacingVector until it is facing the NewFacingVector

```
if(isTurning)
{
    if(Math.abs(UnitAngle - NewAngle) < TurningRate)
    {
        UnitAngle = NewAngle;
        isTurning = false;
    }
    // NOTE: you'll eventually want a TurningRight or TurningLeft instead of just isTurning)
    else
    {
        UnitAngle -= TurningRate;
    }
}

```

And that should do it; and best of all, it'll do it without re-calculating ArcTan several times (which is expensive.)

When having multiple moving entities, I'd probably only update "NewAngle" every second or so so that you can leverage the most out of your ArcTan calls. This can eventually be a more sophisticated approach where you track if you and/or the target are moving and update more or less frequently based on that possibly.

---
Tags: c#, mathematics, rotation
---


title: Why is Game Logic so Decentralized

text:
# Question
Title: Why is Game Logic so Decentralized
So I've dipped my toe in and out of game programming pretty regularly over the past few years and all of the tutorials I've watched and books I've read have all had one thing in common that perplexed me.

Most of the logic in the games I've seen built is completely decentralized and distributed among the various components of the game. There isn't one (or several) central controller(s) that guide how everything interacts with everything else, or that objects and methods in the game defer to to enforce the rules/design.

If an object in a game (a player object for example) impacts a broader game system by say, resetting the level when it reaches 0 health, it doesn't call to some "LevelController" or "LevelController -\> GameController" which then resets the level, it just does it itself by directly accessing a built-in game engine directive/method call.

Almost all the actions and interactions from initialization and set up, to combat, collisions, etc. are all resolved in a sort of case-by-case individual bases with all the rules contained solely within various game objects and the only "oversight" being the inherent limits of the game engine itself.

As someone who comes from a pretty traditional top-down Object Oriented development background this whole methodology feels scattershot and piecemeal. It has made it difficult for me to design any kind of holistic architecture for my game projects.

Is it just the case that most intro level projects are like this because they focus on the basic components of a game and how they work and less on more complex, higher level design? Or is it the nature of game design/development in general, perhaps a necessity due to the unique nature of the complexity of games?

# Answer
> 4 votes
Most basic tutorials try to keep things simple. They want to demonstrate an API, not take an hour to create an over-engineered software architecture and *then* proceed to explain the things the audience actually came to learn. So they instead try to demonstrate the most simple way to do a simple thing. An experienced software engineer will then decide on their own how to best build an architecture to encapsulate all these building blocks of a more complex game.

But nevertheless, there is one core difference between developing a business application and developing a game. Game development is a far more creative process.

When you create a business application, then your product owner expects you to create an application which fulfills a very specific purpose. You usually have a precise and detailed list of requirements. That allows you to plan well. A software architect can design their software architecture down to the class level and then hand their UML diagrams to a herd of code monkeys to program it. You then hand the resulting program and your requirements to your testers, and when they made a check-mark behind every requirement, you ship your software.

But with game development, your only requirement is "fun" (and maybe to get the player to spend money on microtransactions, if you are in that part of the industry). You usually *do* have some idea what you want your game to be. But the finished game might still turns out to be substantially different than your original game design concept. You intended to develop an RTS, went a bit over board with your unit progression systems and storytelling, decided to ditch base building and ended up with what feels more like an RPG? So what? As long as it is fun to play, you have a product which will sell.

That means game design is usually a far more iterative process. You want to try out all kinds of ideas for game mechanics, testplay them, see what sticks and discard the rest. In order to allow a short design-\>develop-\>test-\>redesign cycle, you need to be able to make quick changes to your game. The more you over-engineer your architecture, the harder it can be to do experiments you didn't anticipate.

Sure, if you neglect architecture completely, you might soon find yourself in an unmaintainable and undebugable mess of code. Many game development projects fall into that trap. This is why game developers came up with some software architecture patterns of their own which bring some structure in a codebase but still allow fast iterations.

One very common architectural pattern in game development is the Entity - Component - System pattern. It does a great job at loosely coupling different game systems and makes it very easy to mix and match them. Yes, it means that your game mechanics are distributed over multiple separate systems, but that separation allows you to add, develop and remove each game mechanic independently from the others.

I am looking forward to playing your games.

---
Tags: game-design, architecture
---


# Question
Title: ScreenToWorldPoint returning wrong position even when given Z plane
I have a NavMeshAgent placed on a character model. When I log `agent.transform.position` I get `(4.5, 0.1, 4.5)` which is correct (this is a 2.5d game and movement happens along the x and z axes).

I am trying to set up a script so that when I click a location on the screen, the character will turn to face that location.

The problem I'm facing is that the coordinates returned by `Camera.ScreenToWorldPoint` are not correct:

```
Vector3 mousePos = Input.mousePosition;
mousePos.z = Camera.main.nearClipPlane;
Vector3 targetPos = Camera.main.ScreenToWorldPoint(mousePos);

Debug.Log(agent.transform.position)
// Logs: (4.5, 0.1, 4.5)

Debug.Log(targetPos)
// Logs: (0.1, 16.7, 0.7)

```

In this example, I'm clicking on the same place as the agent but the targetPos is not nearly the same.

The y-axis of `targetPos` is static (the same no matter where I click), which seems correct. However the values for x and z are not correct. How do I get the correct coordinates for a click?

*edit* I have this workaround, but I want to know how to solve the original question still:

```
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, rotateTargets))
{
    Vector3 targetPos = hit.point;
    targetPos.y = agent.transform.position.y;
    Vector3 direction = (targetPos - agent.transform.position).normalized;
    Quaternion rotation = Quaternion.LookRotation(direction);
    agent.transform.rotation = rotation;
    agent.updateRotation = false;
    return true;
}

```

# Answer
> 1 votes
I needed to use `Camera.main.position.y - agent.transform.position.y` as the value for z on `ScreenToWorldPoint`.

The reason is that the z argument in this case should be *the distance between the camera and the ground*, not *the ground's position relative to 0*.

---
Tags: unity
---


# Question
Title: Intel GPU running faster than Nvidia GTX 1060
My app in its current state renders only 2 triangles to the screen using OpenGL. I am using `std::chrono::steady_clock` for frame counting.

With Intel graphics, I hit 1000fps and with my GTX 1060(6GB) I am getting an absurd frame rate of 480fps.

I have used the Nvidia Optimus Enablement method to force renders on my GPU(reference: http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf)

Why could this be happening? My shaders are under 60 lines of code, there seems to be nothing that is lagging my GPU from my CPU performance.

# Answer
**This is perfectly normal with light workloads**,

The way Optimus works is that, when using the NVIDIA, it does all of the heavy work on that, then transfers the final framebuffer to the Intel for display. On the other hand, if using the Intel only, this transfer does not happen.

All that you are seeing is that the amount of work you are doing is so small that the transfer is the dominant factor in your performance. As you do more work, you will see things even out and eventually the NVIDIA will pull ahead.
> 0 votes

---
Tags: opengl, c++, rendering, frame-rate
---


# Question
Title: Can a Game Engine be built into a Game Engine?
This confuses me as the title says "Mostly Civilized: A Hex-Based 4x **Game Engine for Unity** \- Part 1"

Unity is a Game Engine, and he is building a game engine for a game engine.

Did he word this incorrectly, or is building a game engine into a game engine a real thing?

# Answer
> 10 votes
The word *engine* is somewhat ambiguous. It can be used broadly to mean any integrated development environment for building games. Or it can be used specifically to describe the framework of a particular game or type of game.

Here are two sentences illustrating the difference:

1. Unity is a great engine for building all kinds of games. **GENERAL.**
2. When they remastered Shadow of the Colossus, they rebuilt their original engine. **SPECIFIC.**

Unity is a game engine in the broadest sense. It can be used to make games.

But you might write up something in Unity that is well-suited to make a particular type of game, for example a first-person shooter. Then you would have made a *first-person shooter engine* that others could use to make first-person shooters. Similarly, you could write something in Unity that is well-suited for making hex-based games, in which case you'd have a *hex-based engine*.

This ambiguity makes sense when you think of an *engine* as any piece of software with "an encapsulated block of functionality" (here), since you can always construe these blocks of functionality as coarsely or as finely as you'd like.

# Answer
> 4 votes
There are really two different meanings for (game) engine today. Categorical definitions are often nebulous, but here's the feeling I've picked in 30 years of orbiting the industries.

Unity already contains dozens of things we call engines. There's a Particle Engine, a Physics Engine (two of them!), an Animation Engine, an Audio Engine, and a UI Engine at the least. The object management system and rendering subsystem might also count.

In this form, "engine" means "a usually-reusable/modular system, component, framework, module, or library designed to manage the ongoing transformations of your persistent state based on inputs or rules." Things outside of games use the term sometimes too; I've seen plenty of HTML renderer and database and widget/windowing systems being referred to as engines, if not named it in the code.

One thing Unity doesn't come with is a Rules engine or a Mechanics Engine or a Gameplay Engine (unless you're making a pure physics game), and that's what that guy is trying to make. It looks like in later episodes he's working on creating mechanics for city management and stuff, so it's not just about the tile map. But a Tile Map Engine is another thing that Unity doesn't come with.

The other use of the word comes from earlier days, when intentionally making modular components to reuse between games was far less common and largely an in-house affair with things like the Z-Machine and the three or four frameworks Sierra went through over the years. It wasn't until cross-company licensing of the Doom engine broke out that anyone used the term, AFAIK. And back then, it really was one hunk of code that would run your game; you would have to hack it to add new behaviors but most of making a game like Heretic really was feeding new graphics, maps, and audio into the system.

# Answer
> 1 votes
Unity is indeed a game engine. However, it is highly customizable. That's what it means to build an engine on top of unity - to customize it.

Unity does not have any built-in functionality for hexagonal grids. By customizing or adding this to the Unity engine, they have "built their engine into Unity".

---
Tags: unity, architecture, terminology
---


title: Are browser games still profitable?

text:
# Question
Title: Are browser games still profitable?
Back in middle school I would play games like bowman, kitten cannon, sniper assassin, etc. On sites like addictinggames.com, or crazymonkeygames.com.

I know these games would have ads run on them, which I assume was profitable for the developer. Especially titles like those that probably have 8 figure play-stats across the internet.

I was wondering if anyone has any experience with this market, and could provide some insight as to how it is doing now, and what is used to make these games: Is it financially worth developing a browser game? Do I have to use flash to be accepted on these sites?

Back then they were all flash games, but there has been a large uprising of javascript game engines since then (which I am much more familiar with.) But I'm not sure if that's something these sites would accept.

# Answer
> Do I have to use flash to be accepted on these sites?

Flash is dead. The browser vendors killed it and put HTML5+JavaScript in its place. Even Adobe admits that. All the web game portals are moving to HTML5+Javascript games.

> I know these games would have ads run on them, which I assume was profitable for the developer.

Advertisement is one way to monetize smaller games. But the real money is in microtransactions now. Not every game is suitable for microtransations, though. It needs to have enough long term motivation to keep the player engaged for multiple sessions and enough content to warrant paying for.
> 4 votes

# Answer
Here's revenue information for browser-games developer and publisher Plarium:

https://www.owler.com/company/plarium

So yes, I would say it's very very profitable.
> 2 votes

---
Tags: browser-based-games
---


# Question
Title: How to make a car move sharper at high speed?
I am working on a car-racing game on Unity 2018.1. My car works perfectly at low speed but as it speeds up, I lose control over the car and it starts to drift independently. What can I do to prevent this?

# Answer
> 14 votes
I think it can be acheived using different ways :

* Increase the friction on your PhysicsMaterials as Linaith pointed out. It is worth noting that you should have one PhysicsMaterials for your road and one for your tires, and play with the "Friction Combine" parameter ;
* Increase the "drag" and/or "angular drag" value on your rigidbody component ;
* Use a compensation force as explained at 4:50 in this video. The goal is very simple : apply a force to the opposide side of the side you are drifting (slightly smaller to allow a bit of drifting though).

I personnaly went for the last one which gives me more control over the car as I am going for a more arcade gameplay. I believe that the other two are more suited for simulation gameplay.

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


# Question
Title: How do I handle player collision with corners of a wall
I have implemented some basic wall collisions where I project the velocity vector onto the wall the player is colliding with so they slide across the wall. The problem I am having is when you slide into the corner of a wall the player goes through the wall. What am I missing? Am I using the wrong method for this type of collision.

You can see the code at it's original location or below:

```
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var lastTime = Date.now();
var deltaTime = 0;
var sector = {
    walls: [
        {
            start: {
                x: 150,
                y: 100
            },
            end: {
                x: 300,
                y: 100
            }
        },
        {
            start: {
                x: 300,
                y: 100
            },
            end: {
                x: 350,
                y: 150
            }
        },
        {
            start: {
                x: 350,
                y: 150
            },
            end: {
                x: 350,
                y: 300
            }
        },
        {
            start: {
                x: 350,
                y: 300
            },
            end: {
                x: 300,
                y: 350
            }
        },
        {
            start: {
                x: 300,
                y: 350
            },
            end: {
                x: 150,
                y: 350
            }
        },
        {
            start: {
                x: 150,
                y: 350
            },
            end: {
                x: 100,
                y: 300
            }
        },
        {
            start: {
                x: 100,
                y: 300
            },
            end: {
                x: 100,
                y: 150
            }
        },
        {
            start: {
                x: 100,
                y: 150
            },
            end: {
                x: 150,
                y: 100
            }
        }

    ]
}
var player = {
    rotation: 180,
    radius: 20,
    moveSpeed: 1,
    turnSpeed: 90,
    maxSpeed: 1,
    friction: 2,
    speed: {
        x: 0,
        y: 0,
        z: 0
    },
    position: {
        x: 200,
        y: 200,
        z: 0
    }
}
var keys = {
    backspace:      8,
    tab:            9,
    enter:          13,
    shift:          16,
    ctrl:           17,
    alt:            18,
    pause:          19,
    capslock:       20,
    escape:         27,
    space:          32,
    pageUp:         33,
    pageDown:       34,
    home:           36,
    end:            35,
    left:           37,
    up:             38,
    right:          39,
    down:           40,
    insert:         45,
    del:            46,
    zero:           48,
    one:            49,
    two:            50,
    three:          51,
    four:           52,
    five:           53,
    six:            54,
    seven:          55,
    eight:          56,
    nine:           57,
    a:              65,
    b:              66,
    c:              67,
    d:              68,
    e:              69,
    f:              70,
    g:              71,
    h:              72,
    i:              73,
    j:              74,
    k:              75,
    l:              76,
    m:              77,
    n:              78,
    o:              79,
    p:              80,
    q:              81,
    r:              82,
    s:              83,
    t:              84,
    u:              85,
    v:              86,
    w:              87,
    x:              88,
    y:              89,
    z:              90,
    select:         93,
    numpad0:        96,
    numpad1:        97,
    numpad2:        98,
    numpad3:        99,
    numpad4:        100,
    numpad5:        101,
    numpad6:        102,
    numpad7:        103,
    numpad8:        104,
    numpad9:        105,
    multiply:       106,
    add:            107,
    subtract:       109,
    decimal:        110,
    divide:         111,
    f1:             112,
    f2:             113,
    f3:             114,
    f4:             115,
    f5:             116,
    f6:             117,
    f7:             118,
    f8:             119,
    f9:             120,
    f10:            121,
    f11:            122,
    f12:            123,
    numlock:        144,
    scrollLock:     145,
    semicolon:      186,
    equal:          187,
    comma:          188,
    dash:           189,
    period:         190,
    forwardSlash:   191,
    graveAccent:    192,
    openBracket:    219,
    backSlash:      220,
    closeBraket:    221,
    singleQuote:    222
}
var key = {
    up: false,
    down: false,
    left: false,
    right: false,
    down: [],
    next: []
}

/*==================================================
    CORE CODE
==================================================*/
function toRadians(degrees){
    return degrees * Math.PI / 180;
}

function update(){
    updateTime();
    updateKeyboard();
    updatePlayer();
    clearCanvas();
    drawPlayer();
    drawSector();

    window.requestAnimationFrame(update);
}

window.requestAnimationFrame(update);

function clearCanvas(){
    context.clearRect(0, 0, canvas.width, canvas.height);
}

function updateTime(){
    var currentTime = Date.now();
    deltaTime = (currentTime - lastTime) / 1000.0;
    lastTime = currentTime;
}

function lineIntersection(a, b, c, d){
    var denominator = ((b.x - a.x) * (d.y - c.y)) - ((b.y - a.y) * (d.x - c.x));
    var numerator1 = ((a.y - c.y) * (d.x - c.x)) - ((a.x - c.x) * (d.y - c.y));
    var numerator2 = ((a.y - c.y) * (b.x - a.x)) - ((a.x - c.x) * (b.y - a.y));

    if (denominator == 0) return numerator1 == 0 && numerator2 == 0;

    var r = numerator1 / denominator;
    var s = numerator2 / denominator;

    return (r >= 0 && r <= 1) && (s >= 0 && s <= 1);
}

/*==================================================
    PLAYER CODE
==================================================*/
function updatePlayer(){
    if(key.down[keys.up]){
        player.speed.y = Math.max(-player.maxSpeed, player.speed.y - player.moveSpeed * deltaTime);
    }
    else if(key.down[keys.down]){
        player.speed.y = Math.min(player.maxSpeed, player.speed.y + player.moveSpeed * deltaTime);
    }
    else {
        friction();
    }

    if(key.down[keys.left]){
        player.rotation = player.rotation - player.turnSpeed * deltaTime;
    }
    else if(key.down[keys.right]){
        player.rotation = player.rotation + player.turnSpeed * deltaTime;
    }

    var radians = toRadians(player.rotation);
    var move = {
        x: Math.cos(radians) * player.speed.y,
        y: Math.sin(radians) * player.speed.y
    }

    var remainder = moveRemainder(move);

    player.position.x += remainder.x;
    player.position.y += remainder.y;
}

function moveRemainder(move){
    var remainder = move;

    var currentPosition = {
        x: player.position.x,
        y: player.position.y
    }
    var nextPosition = {
        x: player.position.x + move.x,
        y: player.position.y + move.y
    }

    var checkWalls = function(index){
        for(var i=0; i<sector.walls.length; i++){
            var wall = sector.walls[i];
            if(lineIntersection(currentPosition, nextPosition, wall.start, wall.end)){
                var xLength = Math.max(wall.start.x, wall.end.x) - Math.min(wall.start.x, wall.end.x);
                var yLength = Math.max(wall.start.y, wall.end.y) - Math.min(wall.start.y, wall.end.y);
                var equation = (move.x*xLength + move.y*yLength) / (xLength*xLength + yLength*yLength);

                remainder.x = xLength * equation;
                remainder.y = yLength * equation;
                if(index == 0){
                    checkWalls(1);
                }
                return;
            }
        }
    }
    checkWalls(0);

    return remainder;
}

function drawPlayer(){
    context.beginPath();
    context.fillStyle = 'red';
    context.arc(player.position.x, player.position.y, 3, 0, Math.PI * 2);
    context.fill();
    context.closePath();
}

function friction(){
    if(player.speed.x < 0){
        player.speed.x = Math.min(0, player.speed.x * deltaTime);
    }
    else if(player.speed.x > 0){
        player.speed.x = Math.max(0, player.speed.x * deltaTime);
    }
    if(player.speed.y < 0){
        player.speed.y = Math.min(0, player.speed.y + player.friction * deltaTime);
    }
    else if(player.speed.y > 0){
        player.speed.y = Math.max(0, player.speed.y - player.friction * deltaTime);
    }
}

/*==================================================
    SECTOR CODE
==================================================*/
function drawSector(){
    context.strokeStyle = 'black';
    sector.walls.forEach(function(wall){
        context.beginPath();
        context.moveTo(wall.start.x, wall.start.y);
        context.lineTo(wall.end.x, wall.end.y);
        context.stroke();
        context.closePath();
    })
}

/*==================================================
    INPUT CODE
==================================================*/
function updateKeyboard(){
    key.down = key.next;
}

window.addEventListener('keydown', function(e){
    key.next[e.keyCode] = true;
})

window.addEventListener('keyup', function(e){
    key.next[e.keyCode] = false;
})
```

```
<!doctype html>
<html>
    <head>
        <title>Retro3d proof of concept</title>
        <style>
            body {
                margin: 0;
                background: #f4f6f8;
            }
            #canvas {
                margin: 20px auto;
                display: block;
                background: #fff;
                border-radius: 2px;
                box-shadow: 0 0 0 1px rgba(63,63,68,0.05), 0 1px 3px 0 rgba(63,63,68,0.15);
            }
        </style>
    </head>
    <body>
        <canvas width="600" height="600" id="canvas"></canvas>
        <script src="main.js"></script>
    </body>
</html>
```

# Answer
> 2 votes
I saw a couple problems in your `checkWalls` function:

Once `lineIntersection` triggers for one wall, you `return` \- this means once the check is positive for one wall you don't check for the second wall that would be needed for the corner check - dirty fix by moving the `return` outside the loop.

Without putting too much brainpower into fully understanding the math in `lineIntersection`, you seem to run into an "edge"(haha)-case that the velocity vector and the second line actually do NOT intersect - fixed by having the lines overlap.

https://jsfiddle.net/x0s0ef0b/41/

This is not bulletproof since I was able to have the player escape with those two fixes in place but it should hint you in the right direction. Also there is now some optimization to be done (you are now always checking all wall, which is not necessary). Instead of intersection you might want to check for "being on the outside of a wall" (e.g. if you always construct the levels clockwise, being on the left side of the wall).

Also I commented out the

```
if(index == 0){
  //checkWalls(1);
}

```

part, because I did not understand why you would want to run the check twice (and it still seemed to work).

# Answer
> 1 votes
Finally figured out how to get this to work. I added a circle collision to the player. Example can be found here jsfiddle.net/CalinR/3augx250 What I'm doing is projecting the player position onto the wall and if the distance between the projection and the player is less than the player radius I get the normal of the wall and multiply it by the player radius to get the new position of the player

---
Tags: collision-detection, javascript, html-canvas
---


# Question
Title: Does gluLookAt add or set the view matrix variables?
I'm trying to rotate the camera view in PyOpenGL, but it's not working well. The weirdest behavior I've noticed is that putting gluLookAt in a loop seems to change the camera view, even when I'm not changing the inputs as the loop continues.

So while I'd expect something like:

```
gluLookAt(0,0,0, 0,0,-5, 0,0,1)

```

to keep the camera constantly pointing downwards, it seems to rotate the view in some strange way, with the objects being rendered leaving the maximum clipping radius after a while.

My question is, does gluLookAt take into account the previous camera settings, or do I need to look for something else wrong in my code?

# Answer
> 1 votes
https://www.khronos.org/opengl/wiki/GluLookAt\_code

gluLookAt computes a matrix and multiplies it with the current matrix. You need to use glLoadIdentity before using gluLookAt, in other words.

---
Tags: opengl, camera
---


title: Teleport Not Working in Unity 2D

text:
# Question
Title: Teleport Not Working in Unity 2D
So I'm basically trying to get my character to "use" a set of stairs by teleporting from one stairway door to another. Each stairway door will be paired with one other stairway door.

Here's the code, I feel like it should be working...my Debug.Logs are even outputting the correct information. Also FYI, I have the Transform doorPairedWith as public so that I can just drag and drop the stairway door that each one is supposed to be paired with.

```
 using UnityEngine;

 public class Stairs : MonoBehaviour {

 Player player;

 public Transform doorPairedWith;

 Vector3 doorPairedWithPosition;
 Vector3 playerPosition;

 BoxCollider2D playerCollider;
 BoxCollider2D stairsTriggerCollider;

 bool playerIsNearStairs = false;

 void Start()
 {
     player = Player.instance;

     playerPosition = player.transform.position;
     doorPairedWithPosition = doorPairedWith.position;

     playerCollider = player.GetComponent<BoxCollider2D>();
     stairsTriggerCollider = GetComponent<BoxCollider2D>();
 }

 void Update()
 {
     UseStairs();
 }

 void UseStairs()
 {
     if (playerIsNearStairs == true)
     {
         if (Input.GetKeyDown(KeyCode.E))
         {
             Debug.Log("Attempting to use stairway door named: " + doorPairedWith);
             playerPosition = doorPairedWithPosition;
         }
     }
 }

 void OnTriggerEnter2D(Collider2D collision)
 {
     if (collision.gameObject.tag == "Player")
     {
         playerIsNearStairs = true;
         Debug.Log("Player is near stairs: " + playerIsNearStairs);
     }
 }

 void OnTriggerExit2D(Collider2D collision)
 {
     if (collision.gameObject.tag == "Player")
     {
         playerIsNearStairs = false;
         Debug.Log("Player is near stairs: " + playerIsNearStairs);
     }
 }
 }

```

# Answer
Vector3s are not reference type. The actual GameObject will not move until you modify that object's transform.

UseStairs sets playerPosition, but never sets player.transform.position to the new data.

your code should look something like this.

```
void UseStairs()
{
     if (playerIsNearStairs)
     {
         if (Input.GetKeyDown(KeyCode.E))
         {
             Debug.Log("Attempting to use stairway door named: " + doorPairedWith);
             player.transform.position = doorPairedWithPosition;
         }
     }
}

```
> 2 votes

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


title: Java Game Loop Efficiency

text:
# Question
Title: Java Game Loop Efficiency
I was watching 2 video tutorials on how to make java game and read a couple articles about game loop. However, I'm still confused about how game loop actually works.

The first tutorial used code that looked like this (I modified some codes from the tutorial and commented on top):

```
/*
 * Game Loop of the game. It uses fixed timestep.
 * Optimal time represents time needed to update one frame.
 * Update time represents time actually taken to update one frame.
 *
 * By calculating the difference between optimal and actual time,
 * we can let Thread to sleep for the exact time we are aiming for, which is 60 FPS.
 */

public void run() {
    long now;
    long updateTime;
    long wait;

    final int TARGET_FPS = 60;
    final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

    while (isRunning) {
        now = System.nanoTime();

        update();
        render();

        updateTime = System.nanoTime() - now;
        wait = (OPTIMAL_TIME - updateTime) / 1000000;

        try {
            Thread.sleep(wait);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

```

This is quite easy to understand and I have no problem with using this game loop. However, the second tutorial used more complex game loop that I had a hard time understanding it:

```
public void run() {
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0 ;
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            tick();
            delta--;
        }
        if(running)
            render();
        frames++;

        if(System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println("FPS: " + frames);
            frames = 0;
        }
    }
    stop();
}

```

I do not understand the use of *timer* and *frames* variable and how *delta* is being used. Is *timer* and *frames* simply used for printing out the FPS on the console screen? Also, help me clarify the use of *delta* variable in this code.

The use of *delta* variable is quite different from the other game loop that I know of. From the articles that I read, I've seen a different use of delta. Here is what I tried to come up with on my own after reading the articles:

```
/*
 * Delta is ratio of how fast computer is running.
 * It is achieved by calculating:
 * (actual time) / (optimal time)
 *
 * This is passed to update method to calculate time taken
 */

public void run() {
    long lastLoopTime = System.nanoTime();
    final int TARGET_FPS = 60;
    final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;

    while (isRunning) {
        long now = System.nanoTime();
        long updateTime = now - lastLoopTime;
        lastLoopTime = now;

        double delta = updateTime / (double) OPTIMAL_TIME;

        update(delta);
        render();
    }
}

```

Will the above code be fine as it is?

Out of these three sets of codes, which game loop would be the most optimal to use?

# Answer
---

## Comparison of the three versions

**First version**

The first version of the code, there is no measure of the elapsed time since last update. That would usually make the game frame rate dependent. It is compensated by inserting waiting via `Thread.Sleep`, which will give you a fixed timestep on a fast machine. Which is good in that it prevents the render thread to eat CPU time.

By the way, we usually update first to have something to render on the first iteration, also we do not want waits between update and render.

**Note**: The time the system does not guarantees to preempt the thread for exactly the time you in `Thread.Sleep`.

**Second version**

The second game loop does not pass the elapsed time either, instead it will let render happen as fast as it can and call update (tick) at a steady frequency, making the game stable. It also includes a simple FPS counter. *Advanced FPS counters are beyond the scope of this answer.* This version of the game loop is better if you want to debug the render performance (see how fast you can get it to run), however, it is not optimal.

The check of `running` before calling render, is there because update (tick) can change `running` (notice `running` is not local), and since the call to render happens after, this prevents an extra call. Should not be a problem, assuming teardown happens inside of the stop method. If it were a problem, I would break the loop instead.

About the use of the variable `timer`, as you may know, you can simulate timers in the update method by this technique. However, I would recommend to use the approach used for `delta`, because it avoids possible overflows on a long run. In fact, you may want to avoid `System.currentTimeMillis` because it is susceptible to changing the system clock.

**Third version**

The third code (the one you came up with) will also let rendering happen as fast as it can, and passes the elapsed time to the update method. Yet, it does not control the update rate.

---

**About the naming of delta**

In the second version, `delta` is an accumulator that is used to decide when to call update (tick). On the last version, it is the elapsed time. Usually `delta` means the latter. I have also seen game loops that name the former `delta` because it is the time elapsed since the last call to update.

---

## Picking a game loop

Now, should you use a fixed timestep (like the first version), or should you use a variable timestep (like the others)?

**Fixed timestep**

*The first version*

First, the fixed timestep will serve you better if you know the target hardware. As I said, it will prevent the render thread to eat too much CPU, which is good on slow machine, which probably will have a low frame rate also.

Another advantage is that the physic computations are simpler, because you are not taking the elapsed time from the last frame. That also means that any variance in update time will be more noticeable.

However, it may not age well, for instance if you make your game for 30 or 60 FPS when people are expecting 120 FPS.

Thus, if you do not know the hardware, I would advise to make the timestep a configurable option... yet, you would have to take that into account for the update (remember that in the first version, the update does not take the elapsed time).

**Semi-fixed timestep**

*Not represented on the question*

You take the structure of the fixed timestep approach, and still measure the elapsed time from the last update, and still use it to decide if you call update or not... but you may also pass it to the update method.

You would lose the simple physics (which is probably good if your game requires complex physics anyway), you will still be saving CPU time, and you will be accounting for any variance in the update times.

The target timestep is still something you control.

**Variable timestep**

*The second version controls the update rate, the third does not*

With this version, the game will run as smooth as the system allows it, meaning it will have a render rate as high as possible. It has the *drawback* of requiring *actual* physics computations that use the elapsed time.

There is no way to configure the render rate; you may still control the update rate.

If you let the update rate be variable, it can give you problems with fast moving objects, in particular on slow hardware. The elapsed time could mean that objects moved a long distance and you would have to resolve a large amount of collisions per frame, dragging the performance.

While keeping the update rate variable, a common approach is to have a maximum of collision you solve. However, that can lead to objects tunneling through other objects or getting out of bounds. An alternative is to clamp the elapsed time. That would make the game go slower (things move at a lower speed) on slow hardware.

---

## Beyond the game loop

First, do not expect to create a game loop that fits every game. In fact, some games can work perfectly by listening the events provided by the widget library (that is still a loop, but you did not write it). Each game loop has its tradeoffs, and it is a good idea to test and profile on the target hardware.

---

With that said, here are some other considerations:

1. For an Android game, you may want to implement a `pause` field, that if set, you do not call update. You would then update it according to the activity lifecycle.
2. You can take advantage of threading, in particular to call subsystems that require more time than one update. *The mechanism for this are beyond the scope of the answer.*

However, I want to note that threads will compete for CPU time with the game loop, in that case having a call to `Thread.Sleep` in the game loop will help, even if only `Thread.Sleep(0)`. In fact, insert a `Thread.Sleep(0)` at the end of the loop, even in the fixed timestep approach, in case the system is too slow that it never reaches the `Thread.Sleep` you already had.
3. Another thing you can do is have the render method be aware of the elapsed time. In particular, if you have a fixed timestep or if you control the update rate, you can compute the time for the next update... with that, you compute the fraction of the time to the next update that has elapsed, and pass it to the render method. The render method would then pass it to the shader as a uniform, allowing animations to happen in GPU. This can give you smooth animation regardless update rate, making them great for the fixed timestep approach... you upload the fraction, the old state and the new state to the GPU, and let it interpolate (fantastic for morph target animation).
4. Finally, consider breaking the interaction with every external system. Such as getting input, playing sounds, etc. Those are not exactly rendering, and are not exactly updating.
> 6 votes

---
Tags: java, game-loop
---


# Question
Title: How can I synchronize state in my Asteroids game with many networked players?
Wondering how state synchronization works in games with lots of players like MMOs. It seems like a hard problem to solve and I am not aware if there are standard solutions. Specifically, synchronizing game clients (users playing game) with an array of centralized servers, and then broadcasting and merging the state with all the same connected clients. How it is done (and how efficiencies are implemented) typically, and what the structure of the game state is like.

To simplify this question, I am thinking in terms of a simple asteroids game:

You have n number of players, and the asteroids, players, and bullets are synchronized across clients. I am not familiar with how the game state should be modeled (if it's some quadtree thing you are sending around, or just a vector of patch/updates, etc.). There could be players all over the world, so latency is a factor.

# Answer
# Is it possible to save the game's current state to disk?

If *yes* (hint, the answer is always yes) then you have a means by which you can synchronize players. Even if it is horribly inefficient. But optimization is just a matter of working out which bits and bytes any given player doesn't need, either because:

* they *already know* (eg, what level is being played and it hasn't changed)
* they are the data *source* (eg a player doesn't need their own user name)
* they *can't know* (eg stealthed players in WoW are not sent to other players *until detected* otherwise someone could write an external program that could detect and display that information, bypassing the mechanic1 )
* they don't *need to know* (eg. That other player on another level is irrelevant)

If *no*, you need to refactor.

1 The "stealth broken" / "hidden player detected" sound effect was actually an accident of this. When the client got told about the stealthed player, it spawned them an *immediately applied all of their buffs,* playing the associated sound effect for each one. This was fixed during development to only play the "entering stealth" sound to avoid eat-bleed, but the audible clue hasn't been planned and ended up being an elegant solution to an unknown problem.
> 3 votes

---
Tags: mmo, synchronization, game-state
---