title: Unity3D (5.1) NavMesh Agent Error

text:
# Question
Title: Unity3D (5.1) NavMesh Agent Error
This is my first post in GameDev StackExchange, so please excuse me if I make any mistakes on best practices here (if I do, please refer me so I can learn).

I'm making a prototype where I have 2 types of enemy units: Uninfected and Infected. The Uninfected are to seek out Infected via AI pathfinding. However, I came across an issue when implementing the NavMesh in the scene. If the Player collides with an Uninfected, they go flying backwards. If they hit the walls, the walls collectively get hit. Here's some screenshots.

Example 1: http://s7.photobucket.com/user/Korudo/media/GameDev/RoboInfect%20Scene%20-%20WallWeirdness1\_zpsg0k2wbyk.png.html

Example 2: http://s7.photobucket.com/user/Korudo/media/GameDev/RoboInfect%20Scene%20-%20WallWeirdness1\_zpsg0k2wbyk.png.html

Thanks in advance.

# Answer
I don't know what u tried and what exactly could be your problem but I would suggest you check if all the navmesh is baked properly and you could also change a few things in NavMeshAgent properties and see if it gets fixed. You could also prevent collision between navmesh agent and the player via NavMeshAgent properties or scripting.
> 0 votes

---
Tags: unity, navmesh
---


# Question
Title: Is a separate thread for game loop compulsory for simple games?
I am new to game development. In order to learn I am recreating this game on android platform. You can observe the game-play video at the above link. It is a simple game.

I have read a lot of articles on getting started with game development.Almost all of them recommended using a game loop on separate thread, which makes sense for other games. However, for this particular game do I need to start a separate thread ?

# Answer
> 8 votes
A game loop is generally recommended because it is *simple*. Almost any game can be properly developed and ran by utilizing a loop, and most games would require one to properly function.

For example, most physics engines require reliable constant updates for a proper simulation. Animations and other dynamic content and graphics need to be updated *every* change, etc... Aka something you get practically free by using a loop.

Now do be aware that your loop doesn't have to run on a separate thread. In fact most games will run the loop on the main thread for simplicity. Even my Android projects follow this principle.

Now the real question here is what alternative do *you* propose? If you have another idea for how to reliably get input, do updates, and draw frames that *works for you* then go ahead! Otherwise a game loop might be the easiest way to get going.

# Answer
> 5 votes
**No**, a separate thread is not required. If you're not doing anything too intense (which doesn't look like that's the case in the game you've shown us), everything can be done on the main thread.

A second thread is required if you're doing a lot of processing or otherwise experiencing issues with the UI/input becoming unresponsive. For example, in more complex games, you don't want the UI/input to become unresponsive when the AI is calculating its next move. Since your game appears to be primarily responding to user input and updating visuals, a second thread is not required.

---

*Answering the "Is a loop required" original question.*

**No**, but the alternatives are more complicated, harder to implement and rarely used.

Games are by definition interactive. At the minimum, that's waiting on input and updating output. The simplest way to do that is a with a loop. It's not required to spawn a new thread for that.

Even though the game you've mentioned appears simple, it has interactive visuals and sounds and it constantly updates those based off user input.

There's not a lot of alternatives to a game loop either. Some kind of interrupt based system could be possible. However, such systems increase the complexity and reduce other factors like determinism. There's a reason game loops are so common, they're easy to implement, easy to understand, flexible and do a great job.

# Answer
> 2 votes
Answer to actual question (Does a game loop need to be in a separate thread):

The reason people often recommend using a separate thread is because they don't want heavy processing to interfere with UI interactivity. You are the only one who can tell if a separate thread is needed for *your* game. It entirely depends on the engine and framework if the main game loop in your present design may interfere with the UI's response time. Thought you generally assume it won't (in small projects) unless you have a reason to think otherwise.

Another reason to keep code in seperate threads is to keep code modular and simple. Having two unrelated pieces of code mixed together can often cause code to become less readable and maintainable in the long run.

Does a game loop need to run on it's own separate thread? Possibly. If there is a problem with response time or code and you need multiple UI items to respond regardless of heavy processing or you simply wish to break the code into specific tasks that occur simultaneously for design reasons then go with it. However, it is considered an **advanced** programming practice.

A simple but perhaps not a great example to illustrate is a two player game. You may want to run two instances of a class that handles user input and converts to state changes in player character instance.

Some frameworks encourage/require you to utilize and event/interrupt based system like ActionScript3.0 does. In those case the loop code will normally go to the `OnEnterFrame` event or something similar that occurs 20 - 60 or 120 times per second.

---

Answer to original question (Do I need a main loop):

It all boils down to the program counter. If you are making a game that will run more than a predetermined amount of time and will not generate code as it goes then you will need to kindly request your user's pc to repeat some instructions that it has already processed and what will possibly change in the meantime is the state (the values stored in the game's objects and globals).

Since you know you will need to repeat instructions, there are several ways to complete this task and continually process the same instructions. All these methods involve moving the program counter back to the currently relevant instruction. The most common control flow statements that cause code to be repeated are called loops, another is the `goto` statement which is rarely used in modern code and has a similar effect in this case (completely not relevant to you).

So to answer your previous question, do you need a loop? Yes, you do.

# Answer
> 0 votes
Just to add to some others' answers here, something that no-one has explicitly mentioned: If you do take the risk of running your game loop in a second thread and it becomes unresponsive, you risk the OS terminating your application. That's why it's recommended to use a separate thread. Hence (for example) the NDK's `native_app_glue.c`/`.h` spawns a separate thread for your loop.

---
Tags: android, physics, game-loop
---


# Question
Title: How to setup libGDX project only for Android & iOS?
I have developed some applications on android.But now i want to learn game development in Android & iOS with libGDX. I want to only develop for Android & iPhone.I do not want a desktop project. All tutorials tell me to first create desktop project than write code in main project & than run as Android application. But i want to write code in android project using both android & libGDX features. Is this possible ? if yes than how ?

# Answer
As far as I know the framework, you code your game once, and it automatically creates an executable for all the platforms. So if you only want to make the game for Android and iOS, you only export the executable for these platforms and ignore the other platforms.

The game also isn't made in the 'desktop' project, it is made in the main project. The 'desktop' project is one of the executables.
> 5 votes

# Answer
When you create an app with gdx-setup, simply select Android and iOS and de-select Desktop and Web options. If you have created them, just ignore them.
> 0 votes

---
Tags: android, ios, libgdx
---


# Question
Title: Garry's Mod HatsChat2 chat colors permissions messed up?
So I'm making a garry's mod server and I'm trying to work on my chat box addon that I installed and was working on that only premium and superadmin can use colors in the chat and only want them to be able to do all the colors below in the code, so here's what I did and edited in my chatbox code:

```
HatsChat = HatsChat or {} --Autorefresh goes weird without the "HatsChat or"
HatsChat.GetPlayerRank = function(ply)
    return string.lower((exsto and ply.GetRank and ply:GetRank()) or --Exsto
        (ply.EV_GetRank and ply:EV_GetRank()) or --Evolve
        (ply.GetUserGroup and ply:GetUserGroup()) or --ULX
        "" --Failed
    )
end

--Editable Vars--
-----------------
--Every variable must keep the same format when you edit it--

--Restrictions
--------------
local DonatorRank = {
    --Chances are I've missed some, add your own donators ranks here. Remember it already runs through a ply:IsAdmin() check too
    ["premium"] = true, ["premium+"] = true, ["premium++"] = true, ["premiumhelper"] = true, ["premiummoderator"] = true,
    ["premiumadmin"] = true, ["premiumsnrmod"] = true, ["premiumdeveloper"] = true, ["none"] = true, ["none"] = true,
    ["none"] = true, ["none"] = true, ["none"] = true, ["none"] = true,
}
local function AdminOnly(ply) return IsValid(ply) and ply:IsAdmin() end --Just an example. Remember, this is client side!
local function DonatorOnly(ply) return IsValid(ply) and (ply:IsAdmin() or DonatorRank[HatsChat.GetPlayerRank(ply)]) end

--Line Icons
------------
HatsChat.LineIcon = {
    --Add your rank icon stuff here
    ["donator"] = "materials/icon16/coins.png", --An example

    --Add specific SteamIDs in this format for single-player icons
    ["STEAM_0:0:0"] = "materials/icon16/shield.png",
    --Example for multiple icons (Experimental)
    ["STEAM_0:0:0"] = {"materials/icon16/heart.png","materials/icon16/shield_add.png"},

    --Defaults
    --These are used if the rank check fails, or if there's no icon for the rank
    ["DefaultSuperAdmin"] = "materials/icon16/shield_add.png",
    ["DefaultAdmin"] = "materials/icon16/shield.png",
    ["DefaultUser"] = "", --Remove this line if you don't want standard users to have line icons

    Global = "", --This icon is used for global messages, not player lines
}

--Chat Colors
-------------
HatsChat.ChatCol = {
    ["[red]"] = Color(255,0,0,255),
    ["[green]"] = Color(0,255,0,255),
    ["[blue]"] = Color(0,0,255,255),
    ["[black]"] = Color(0,0,0,255),
    ["[white]"] = Color(255,255,255,255),

    ["[pink]"] = Color(255,0,255,255),
    ["[teal]"] = Color(0,255,255,255),
    ["[yellow]"] = Color(255,255,0),

    --Minecraft colours
    ["%0"] = Color(0,0,0),      ["§0"] = Color(0,0,0), --Random escape character, the string is actually �0
    ["%1"] = Color(0,0,170),    ["§1"] = Color(0,0,170),
    ["%2"] = Color(0,170,0),    ["§2"] = Color(0,170,0),
    ["%3"] = Color(0,170,170),  ["§3"] = Color(0,170,170),
    ["%4"] = Color(170,0,0),    ["§4"] = Color(170,0,0),
    ["%5"] = Color(170,0,170),  ["§5"] = Color(170,0,170),
    ["%6"] = Color(255,170,0),  ["§6"] = Color(255,170,0),
    ["%7"] = Color(170,170,170),["§7"] = Color(170,170,170),
    ["%8"] = Color(85,85,85),   ["§8"] = Color(85,85,85),
    ["%9"] = Color(85,85,255),  ["§9"] = Color(85,85,255),
    ["%a"] = Color(85,255,85),  ["§a"] = Color(85,255,85),
    ["%b"] = Color(85,255,255), ["§b"] = Color(85,255,255),
    ["%c"] = Color(255,85,85),  ["§c"] = Color(255,85,85),
    ["%d"] = Color(255,85,255), ["§d"] = Color(255,85,255),
    ["%e"] = Color(255,255,85), ["§e"] = Color(255,255,85),
    ["%f"] = Color(255,255,255),["§f"] = Color(255,255,255),

    ["[gray]"] = {r=150,g=150,b=150,a=255, restriction=SuperAdminOnly}, --Restrictions are written out completely differently from normal

    ["[rainbow]"] = {r=255,g=0,b=0,a=255, restriction=SuperAdminOnly, restriction=PremiumOnly}, --Just for fun
    ["[gold]"] = {r=255,g=210,b=50,a=255, restriction=SuperAdminOnly, restriction=PremiumOnly, Glow=true}, --Example for glows
}

--Emotes
--------
HatsChat.Emote = {
    {text=":tux:", icon="materials/icon16/tux.png"},
    {text=":usr:", icon="materials/icon16/user.png"},
    {text=":bomb:", icon="materials/icon16/bomb.png"},
    {text=":box:", icon="materials/icon16/box.png"},
    {text=":cake:", icon="materials/icon16/cake.png"},
    {text=":clock:", icon="materials/icon16/clock.png"},

    {text=":money:", icon="materials/icon16/money.png"},
    {text=":$:", icon="materials/icon16/money_dollar.png"}, --Other currency symbols don't seem to work
    {text=":S:", icon="materials/icon16/money_dollar.png"},
    {text=":E:", icon="materials/icon16/money_euro.png"},
    {text=":Y:", icon="materials/icon16/money_yen.png"},

    {text="<--", icon="materials/icon16/arrow_left.png"},
    {text="-->", icon="materials/icon16/arrow_right.png"},
    {text=":up:", icon="materials/icon16/arrow_up.png"},
    {text=":dn:", icon="materials/icon16/arrow_down.png"},

    {text=":coins:", icon="materials/icon16/user_suit.png", restricted=DonatorOnly},
    {text=":suit:", icon="materials/icon16/house.png", restricted=DonatorOnly},
    {text=":!:", icon="materials/icon16/error.png", restricted=DonatorOnly},
    {text=":date:", icon="materials/icon16/date.png", restricted=DonatorOnly},
    {text=":door:", icon="materials/icon16/door.png", restricted=DonatorOnly},
    {text=":home:", icon="materials/icon16/house.png", restricted=DonatorOnly},
    {text=":cup:", icon="materials/icon16/cup.png", restricted=DonatorOnly},

    {text="<3", icon="materials/icon16/heart.png", restricted=DonatorOnly},
    {text=":?:", icon="materials/icon16/help.png", restricted=DonatorOnly},

    {text=":)", icon="materials/icon16/emoticon_smile.png"},
    {text=">:D", icon="materials/icon16/emoticon_evilgrin.png"},
    {text=":D", icon="materials/icon16/emoticon_grin.png"},
    {text=":(", icon="materials/icon16/emoticon_unhappy.png"},
    {text=";)", icon="materials/icon16/emoticon_wink.png"},
    {text=":3", icon="materials/icon16/emoticon_waii.png"},
    {text=":o", icon="materials/icon16/emoticon_surprised.png"},
    {text=":P", icon="materials/icon16/emoticon_tongue.png"},

    {text=":shield:", icon="materials/icon16/shield.png", restricted=AdminOnly},
}

--Fonts
-------
--*NOTE* Automatic fastdl scripts might not add fonts!
HatsChat.FontData = { --Fonts for chatbox output
    --ManualShadow draws via lua, looks a lot sharper. Without it, most fonts are unusable
    --You can use standard shadows if you wish
    {name = "HatsChatText", font = "Arial", ManualShadow = true},
    {name = "HatsChatPrompt", font = "Arial", size = 15, ManualShadow = true}, --Used in the chatbox prompt
    {name = "Coolvetica", font = "Coolvetica", weight = 500, ManualShadow = true},

    {name = "Roboto", font = "Roboto Bk", weight = 500, ManualShadow = true},

    {name = "Reactor Sans", filename = "resource/fonts/Reactor-Sans.ttf", font = "Reactor Sans", ManualShadow = true}, --filename arg is for custom fonts
    {name = "Pricedown", filename = "resource/fonts/pricedown bl.ttf", font = "pricedown bl", ManualShadow = true},
    {name = "Steelfish", filename = "resource/fonts/steelfish rg.ttf", font = "steelfish rg", ManualShadow = true},
    {name = "Liberation Sans", filename = "resource/fonts/LiberationSans-Regular.ttf", font = "Liberation Sans", ManualShadow = true},
    {name = "Monofur", filename = "resource/fonts/monof55.ttf", font = "monofur", ManualShadow = true},
    {name = "Philosopher", filename = "resource/fonts/Philosopher-Regular.ttf", font = "Philosopher", ManualShadow = true},
}

-----------------------------------------
-------Chat stuff-------
-----------------------------------------
--Editting anything below here may cause instability in the addon

if CLIENT then --For Rainbows!
    local status, inv = 0
    hook.Add( "Think", "HatsChat ChatCol ModifyColours", function()
        local rbow = HatsChat.ChatCol["[rainbow]"]
        local mod = inv and 255-((math.sin( CurTime()*2 )+1) * 127.5) or ((math.sin( CurTime()*2 )+1) * 127.5)
        if status==0 then
            if mod>240 then status = 1 end

            rbow.r = mod --[[High]] rbow.g = 255-mod --[[Low]] rbow.b = 0  --[[Next]]
        elseif status==1 then
            if mod<20 then status = 2 end

            rbow.r = mod  --[[Low]] rbow.g = 0 --[[Next]] rbow.b = 255-mod --[[High]]
        elseif status==2 then
            if mod>240 then status = 3 end

            rbow.r = 0 --[[Next]] rbow.g = mod --[[High]] rbow.b = 255-mod --[[Low]]
        elseif status==3 then
            if mod<20 then status = 1 inv=not inv end

            rbow.r = 255-mod --[[High]] rbow.g = mod --[[Low]] rbow.b = 0 --[[Next]]
        end
    end)
end

for i=1,#HatsChat.ChatCol do
    local tbl = HatsChat.ChatCol[i]
    if type(tbl)=="table" and not (tbl.r and tbl.g and tbl.b) then
        local str, col
        for k,v in pairs(tbl) do
            if type(v)=="string" then
                str = v
            elseif type(v)=="table" and (v.r and v.g and v.b) then
                col = v
            end
        end
        if str and col then
            HatsChat.ChatCol[ str ] = col
            print( "HatsChat.ChatCol badly formatted! Line reformatted to:\t\t[\""..str.."\"] = Color( "..tostring(col.r)..", "..tostring(col.g)..", "..tostring(col.b).."),")
        end
    end
    HatsChat.ChatCol[i] = nil
end
if CLIENT then
    HatsChat.Fonts = {}
    function HatsChat.FormatFont( v, ovr )
        ovr = ovr or {}

        local size = GetConVar("hatschat_text_size")
        size = ovr.size or (size and size:GetInt()) or 15
        local font = surface.CreateFont( v.name or v.font, {
            font = v.font,
            size = math.Clamp(v.size or size,10,100), --Font size overrides settings size
            weight = v.weight or 600,
            blursize = v.blursize or 0,
            scanlines = v.scanlines or 0,
            antialias = v.antialias or true,
            underline = v.underline or false,
            italic = v.italic or false,
            strikeout = v.strikeout or false,
            symbol = v.symbol or false,
            rotary = v.rotary or false,
            shadow = v.shadow or false,
            additive = v.additive or false,
            outline = v.outline or false
        })
        HatsChat.Fonts[ v.name or v.font ] = {ManualShadow = v.ManualShadow}
    end

    for _,v in pairs( HatsChat.FontData ) do HatsChat.FormatFont( v ) end --Format fonts
    for _,v in pairs( HatsChat.Emote ) do v.text = string.lower( v.text ) end --Format emotes
    for k,v in pairs( HatsChat.ChatCol ) do --Format colours
        local str = string.lower( k )
        if str~=k then
            HatsChat.ChatCol[k] = nil
            HatsChat.ChatCol[str] = v
        end
        v.ColorPersists = true
    end
    hook.Add( "InitPostEntity", "HatsChat2 TextSize Init", function() --Re-size and refresh fonts
        for _,v in pairs( HatsChat.FontData ) do HatsChat.FormatFont( v ) HatsChat:RefreshLines() end
    end)
else
    for _,v in pairs( HatsChat.FontData ) do if v.filename then resource.AddFile( v.filename ) end end --Add font files
    for _,v in pairs( HatsChat.Emote ) do if v.icon then resource.AddFile( v.icon ) end end --Add emote materials
    for _,v in pairs( HatsChat.LineIcon ) do if v then
        if type(v)=="table" then
            for i=1,#v do resource.AddFile(v[i]) end
        else resource.AddFile( v ) end
    end end --Add icon materials
end

if SERVER then
    AddCSLuaFile()
    AddCSLuaFile( "hatschat/cl_init.lua" )
    AddCSLuaFile( "hatschat/cl_options.lua" )
    AddCSLuaFile( "hatschat/cl_serverbar.lua" )
    AddCSLuaFile( "hatschat/cl_filter.lua" )

    AddCSLuaFile( "hatschat/sh_themes.lua" )
    AddCSLuaFile( "hatschat/cl_chattags.lua" )

    include( "hatschat/sh_themes.lua" )
elseif CLIENT then
    include( "hatschat/cl_init.lua" )
    include( "hatschat/cl_options.lua" )
    include( "hatschat/cl_serverbar.lua" )

    include( "hatschat/cl_chattags.lua" )
    include( "hatschat/cl_filter.lua" )
    --Client-side sh_themes.lua is included at the bottom of cl_init.lua (autorefresh fix)
end

```

but they can still do all the colors, including \[rainbow\] and \[gold\], etc.

# Answer
> 2 votes
If you still haven't the answer, change your color table to this:

```
HatsChat.ChatCol = {
    ["[red]"] = {r=255,g=0,b=0,a=255, restricted=DonatorOnly},
    ["[green]"] = {r=0,g=255,b=0,a=255, restricted=DonatorOnly},
    ["[blue]"] = {r=0,g=0,b=255,a=255, restricted=DonatorOnly},
    ["[black]"] = {r=0,g=0,b=0,a=255, restricted=DonatorOnly},
    ["[white]"] = {r=255,g=255,b=255,a=255, restricted=DonatorOnly},

    ["[pink]"] = {r=255,g=0,b=255,a=255, restricted=DonatorOnly},
    ["[teal]"] = {r=0,g=255,b=255,a=255, restricted=DonatorOnly},
    ["[yellow]"] = {r=255,g=255,b=0,a=255, restricted=DonatorOnly},

    --Minecraft colours
    ["%0"] = {r=0,g=0,b=0,a=255, restricted=DonatorOnly},       ["Â§0"] = {r=0,g=0,b=0,a=255, restricted=DonatorOnly}, --Random escape character, the string is actually §0
    ["%1"] = {r=0,g=0,b=170,a=255, restricted=DonatorOnly},     ["Â§1"] = {r=0,g=0,b=170,a=255, restricted=DonatorOnly},
    ["%2"] = {r=0,g=170,b=0,a=255, restricted=DonatorOnly},     ["Â§2"] = {r=0,g=170,b=0,a=255, restricted=DonatorOnly},
    ["%3"] = {r=0,g=170,b=170,a=255, restricted=DonatorOnly},   ["Â§3"] = {r=0,g=170,b=170,a=255, restricted=DonatorOnly},
    ["%4"] = {r=170,g=0,b=0,a=255, restricted=DonatorOnly},     ["Â§4"] = {r=170,g=0,b=0,a=255, restricted=DonatorOnly},
    ["%5"] = {r=170,g=0,b=170,a=255, restricted=DonatorOnly},   ["Â§5"] = {r=170,g=0,b=170,a=255, restricted=DonatorOnly},
    ["%6"] = {r=255,g=170,b=0,a=255, restricted=DonatorOnly},   ["Â§6"] = {r=255,g=170,b=0,a=255, restricted=DonatorOnly},
    ["%7"] = {r=170,g=170,b=170,a=255, restricted=DonatorOnly}, ["Â§7"] = {r=170,g=170,b=170,a=255, restricted=DonatorOnly},
    ["%8"] = {r=85,g=85,b=85,a=255, restricted=DonatorOnly},    ["Â§8"] = {r=85,g=85,b=85,a=255, restricted=DonatorOnly},
    ["%9"] = {r=85,g=85,b=255,a=255, restricted=DonatorOnly},   ["Â§9"] = {r=85,g=85,b=255,a=255, restricted=DonatorOnly},
    ["%a"] = {r=85,g=255,b=85,a=255, restricted=DonatorOnly},   ["Â§a"] = {r=85,g=255,b=85,a=255, restricted=DonatorOnly},
    ["%b"] = {r=85,g=255,b=255,a=255, restricted=DonatorOnly},  ["Â§b"] = {r=85,g=255,b=255,a=255, restricted=DonatorOnly},
    ["%c"] = {r=255,g=85,b=85,a=255, restricted=DonatorOnly},   ["Â§c"] = {r=255,g=85,b=85,a=255, restricted=DonatorOnly},
    ["%d"] = {r=255,g=85,b=255,a=255, restricted=DonatorOnly},  ["Â§d"] = {r=255,g=85,b=255,a=255, restricted=DonatorOnly},
    ["%e"] = {r=255,g=255,b=85,a=255, restricted=DonatorOnly},  ["Â§e"] = {r=255,g=255,b=85,a=255, restricted=DonatorOnly},
    ["%f"] = {r=255,g=255,b=255,a=255, restricted=DonatorOnly}, ["Â§f"] = {r=255,g=255,b=255,a=255, restricted=DonatorOnly},

    ["[gray]"] = {r=150,g=150,b=150,a=255, restriction=AdminOnly}, --Restrictions are written out completely differently from normal

    ["[gold]"] = {r=255,g=210,b=50,a=255, restriction=AdminOnly, Glow=true}, --Example for glows
    ["[rainbow]"] = {r=255,g=0,b=0,a=255, restriction=AdminOnly}, --Just for fun
    ["[rainbow2]"] = {r=255,g=0,b=0,a=255, restriction=AdminOnly}, --Using WTE's method
}

```

After you added the above colors, remove all the `["none"] = true,` in your local DonatorRank array. What this will do is, it will allow every rank in the DonatorRank table to access to the chatcolors.

---
Tags: lua
---


# Question
Title: How to implement the server-side game loop?
The server needs to handle the physics, because all the movement will be handled by it. So for that I need a game loop. The thing is that the server doesn't have the render part, it's just a console.

All the posts I found on the internet were involving the render part. I'm not stupid, I know I should not take in consideration that part but then which type of loop should I use? (fixedtimestep, semi-fixed). My game functionality would resemble League Of Legends or Dota 2 functionality.

**Actual questions:**

1.What is the server functionality for this type of game?

2.What does the game loop look like?

**Additional info:** I use libGDX for the client part, and JBox2D on the server part, KryoNet for Networking and thinking of using lwjgl (only the System class) for Native timers.

# Answer
When handling games with a fixed time step, which is what you would need to simulate a physics system, it is best not to go with the system `Timer` as it is not as precise as other methods (even though the difference is small). Here is an example of how you might go about running a game loop that iterates 60 times a second.

```
public void run() {
    double ns = 1000000000.0 / 60.0;
    double delta = 0;

    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();

    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;

        while (delta >= 1) {
            tick();
            delta--;
        }
    }
}

```

The `running` `boolean` would be set to `true` at the start of a program and is better practice than simply putting `true`, especially if there are multiple threads (You would need to have another thread listening for input from clients).

What makes this method better than using a `Timer` is if there is a hiccup or delay in one of the game ticks it is able to compensate. (ie. if the game for whatever reason only iterates 59 times in a second, the next second it will run 61 times) This is important considering the server may fall behind occasionally for whatever reason.

The `tick()` method would consist of all of the code to run the game. (The parts that include movement and such)
> 3 votes

# Answer
The server loop depends on the functionality required by the game. Generally the server is going to be responsible for maintaining an accurate game state because it is usually the authoritative party.

So what does this mean for our server loop? The server loop handles new connections from clients, client transmissions, and automated functionality.

Let's take a look at what the League of Legends in-game server loop might look like at a very high level.

```
void lolServerLoop() {
    if (elapsedtime >= fixedtimestep) {
        // spawn minions
        // update projectile positions
        // update health pools
        // update mana pools

        updateGameState();
            sendGameStateToClients();
        }

        if (clientConnect) {
            registerClient();
        }

        if (clientDisconnect) {
            unregisterClient();
        }

        if (clientActionReceived) {
            validateClientAction();
            applyClientActionToGameState();
        }
    }
}

```

Now this is of course very simple, but the idea here is that you have some actions that happen on intervals (or every tic) such as updating player health or updating projectile positioning, and there are actions that are "triggered" such as updating the game state based on player input.

It might help to first map out the expected responsibilities of the server. For instance, if the server is only responsible each players position, then the loop might look like this.

```
void serverLoop() {
    if (clientActionReceived) {
        validateClientAction();
        updateGameState();
    }
}

```

See how in this case the server only changes the game state when the client sends an action.

It will be worth your time to sit down and figure out all the required functionality before writing code. Experiment a lot using your desired network library starting by implementing simple systems and progressing towards the more complicated ones.
> 3 votes

---
Tags: java, game-loop, server, client-server
---


title: Unity 5 disabling a script

text:
# Question
Title: Unity 5 disabling a script
I'm using Unity 5 and want to disable a script called Unit based on whether the instance is a client or a server. I have tried using:

```
GetComponent("Unit").enabled = false;

```

However I get hit with this error:

> `Assets/Scripts/DisablingUnitScriptIfPlayer.cs(14,46): error CS1061: Type UnityEngine.Component' does not contain a definition for 'enabled' and no extension method 'enabled' of type 'UnityEngine.Component' could be found (are you missing a using directive or an assembly reference?)`

Looking at some tutorials, this worked in previous versions, but I can't find how to make this work for Unity 5. What do I need to change?

# Answer
Please check solution described here

For your case it would be :

```
(GetComponent("Unit") as MonoBehaviour).enabled = false;

```

Warning this will crash if the "Unit" component is not deriving from MonoBehavior (if this is a script you wrote, it should ...)

# EDIT:

The solution proposed by Lohoris in comments is much cleaner and faster, and actuall the official way to do it fom the doc:

*It is better to use GetComponent with a Type instead of a string for performance reasons. Sometimes you might not be able to get to the type however, for example when trying to access a C# script from Javascript. In that case you can simply access the component by name instead of type.*

So the good code is :

```
GetComponent<Unit>().enabled = false;

```

Which will still of course crash if your object has no Unit component.
> 7 votes

# Answer
If you need a safe version of @VB\_overflow's answer, you could do this:

```
MonoBehaviour unit = (GetComponent("Unit") as MonoBehaviour);
if (unit != null)
{
     unit.enabled = false;
}
else
{
     Debug.Log("<color=red>Error:</color> Unit behavior not found, can't disable");
}

```

Here's another version using strong typing based on a comment from @Lohoris, this is more recommended as it is not as fragile to changing of said class:

```
MonoBehaviour unit = GetComponent<UnitBehaviorClass>();
if (unit != null)
{
     unit.enabled = false;
}
else
{
     Debug.Log("<color=red>Error:</color> Unit behavior not found, can't disable");
}

```

That way, if it **does** blow up because of a code change down the road, you'll know why and where to look. Practicing safe handling of possible null references is a good practice to get in the habit of!
> 2 votes

# Answer
You could create a public class of type your script name and then just use this variable and `.enabled = false`.
> 0 votes

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


# Question
Title: How do I get pygame to work on intel processor?
I downloaded Python 3.4 64 bit IDE and pygame but whenever I tried installing pygame it would say "Not supported on Intel". So are there version of pygame available for Intel processor or are there any other ways to install pygame on an Intel processor?????

# Answer
> 1 votes
I see you are running a 64bit version of Python. I tested this, and the version of Pygame you need runs on 32bit Python.

You can go to the Python download page for Python 3.4.3 fromhttps://www.python.org/downloads/release/python-343/
Make sure to download Windows x86 MSI installer.

Then you can download "pygame-1.9.2a0-hg\_5974ff8dae3c+.win32-py3.4.msi" from https://bitbucket.org/pygame/pygame/downloads as Shiro as suggested.

After that you can install Python onto your system, and then pygame. Make sure that if you keep your 64bit version of Python, that you install Pygame to your 32bit version and run Pygame code on the 32bit IDE.

If you don't want to use IDLE, just make sure you have a 32bit version of Python.

Hopefully this helps. :)

---
Tags: python, pygame
---


# Question
Title: Can't draw lines in 2D space with GLFW and OpenGL
I'm trying to draw a grid in 2D space using GLFW and OpenGL but for some reason I only get this on the screen:

Here's my code:

```
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

const int gridSize = 32;

const int SCREEN_WIDTH = gridSize*32;
const int SCREEN_HEIGHT = gridSize*16;

static void inputK(GLFWwindow* window, int key, int scancode, int action, int mods){
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE);
}

static void error_callback(int error, const char* description){
    fputs(description, stderr);
}

int main(void){
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);
    window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "MSSIN_no", NULL, NULL);
    if (!window){
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, inputK);

    while (!glfwWindowShouldClose(window)){
        float ratio;
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;
        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

    //attempt to draw lines
    glBegin(GL_LINES);
    //horizontal
    for (int i = 0; i < SCREEN_HEIGHT; i+=gridSize){
        glVertex2f(0, i);
        glVertex2f(SCREEN_WIDTH,i);
    }
    //vertical
    for (int i = 0; i < SCREEN_WIDTH; i += gridSize){
        glVertex2f(i,0);
        glVertex2f(i, SCREEN_HEIGHT);
    }
    glEnd();

    glfwSwapBuffers(window);
    glfwPollEvents();

    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}

```

# Answer
I fixed it with:

```
 glOrtho(0, width, height, 0, 0, 1);

```
> -1 votes

---
Tags: opengl, c++, graphics, glfw
---


title: Pygame Fullsreen Display Issue

text:
# Question
Title: Pygame Fullsreen Display Issue
Code:

```
import pygame
pygame.init()
#
def Main(display,colors):
    clock =pygame.time.Clock()
    #
    surface = pygame.Surface(surface_resolution) # Create main surface
    surface.fill(colors["RED"])
    pygame.draw.rect(surface,colors["GREEN"],pygame.Rect((0,0),(110,110)))
    pygame.draw.rect(surface,colors["BLUE"],pygame.Rect((10,10),(100,100)))
    #
    while True:
        clock.tick(60)
        #
        for event in pygame.event.get(): # Main event loop
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE: # Exit game with Escape key
                    pygame.quit()
                    return
        #
        display.fill(colors["WHITE"]) # Fill the display white
        display.blit(surface,(display.get_size()[0]/2-surface.get_size()[0]/2,display.get_size()[1]/2-surface.get_size()[1]/2)) # Blit main surface on center of display
        #
        pygame.display.flip()
#
if __name__ in "__main__":
    global resolution
    global surface_resolution
    resolution =         (1920,1080) # Resolution of the display
    surface_resolution = (1536,864)  # Resolution actually seen
    #
    #
    display = pygame.display.set_mode(resolution,pygame.FULLSCREEN) # Create fullscreen display
    #
    colors = {                 # Defign colors
        "WHITE":(255,255,255),
        "RED"  :(255,0,0),
        "GREEN":(0,255,0),
        "BLUE" :(0,0,255),
        "BLACK":(0,0,0)
    }
    #
    Main(display,colors) # Run main loop

```

I have been experimenting with various resolutions in fullscreen Pygame. My new computers native resolution is 1920x1080 as apposed to my old computers resolution of 1366x768, so I started to test resolutions higher than 1366x768. However, when I run pygame with my native resolution, the highest resolution that fits my monitor is 1536x864 with the rest of the primary display off the screen.

This code creates a red surface with a 110x110 rectangle in the upper left corner and blits it to the center of the display. When I set the surfaces size to anything higher than 1536x864, parts of the 110x110 rectangle are cut off, and when I set the display and the surface size to 1366x768, Pygame stretches the display to fill my moniter.

The pygame display docs say that:

> When requesting fullscreen display modes, sometimes an exact match for the requested resolution cannot be made. In these situations pygame will select the closest compatible match. The returned surface will still always match the requested resolution.

However, when I run the following code to get all the available fullscreen resolutions, I see that 1920x1080 is an available resolution.

```
>>> for mode in pygame.display.list_modes():
        print(mode)
(1920, 1080)
(1680, 1050)
(1600, 900)
(1440, 900)
(1400, 1050)
(1366, 768)
(1360, 768)
(1280, 1024)
(1280, 960)
(1280, 800)
(1280, 768)
(1280, 720)
(1280, 600)
(1152, 864)
(1024, 768)
(800, 600)
(640, 480)
(640, 400)
(512, 384)
(400, 300)
(320, 240)
(320, 200)
>>>

```

My question is why does this happen, and how can I stop Pygame from stretching the display in this manner? I feel like I'm completely missing the point with this, but I couldn't find anything about this anywhere else.

# Answer
I managed to find a commit on the Pygame BitBucket page here that explains the issue and gives an example on how to fix it.

What is happening is that some display environments can be configured to stretch windows so they don't look small on high PPI (Pixels Per Inch) displays. This stretching is what causes displays on larger resolutions to display larger than they actually are.

They provide an example code on the page I linked to showing how to fix this issue.

They fix the issue by importing ctypes and calling this:

```
ctypes.windll.user32.SetProcessDPIAware()
true_res = (windll.user32.GetSystemMetrics(0),windll.user32.GetSystemMetrics(1))
pygame.display.set_mode(true_res,pygame.Fullscreen)

```

Calling ctypes.windll.user32.SetProcessDPIAware() will disable the screen stretching. The reason true\_res = (windll.user32.GetSystemMetrics(0),windll.user32.GetSystemMetrics(1)) needs to be called and used for the resolution is because there is fullscreen issues when using a resolution that is not native. If one is using a resolution smaller than this, they can simply create a surface for the game to run on and keep the sides black, or he/she can stretch this surface to fit the display size.

They also express that this is a Windows only solution and is available within base Python since Python 2.4. Before that it will need to be installed.
> 3 votes

---
Tags: pygame, resolution
---


title: Rushing water in Unity

text:
# Question
Title: Rushing water in Unity
How would I go about creating a river with rushing water? I can do the texture around it but I'm stuck on the actual water part. This is in Unity3D.

# Answer
A) First thing you need is River bed mesh You need to create a river mesh by using 3D editing software, like Blender, Maya. If you want to do this in unity you will not get best tools but there many tools available on unity asset store, that provide creating meshes in Unity for example "Easyroads", Mesh toolkit, Prototype.

B) Second you need to create a flow map. which you can create by using free tool "Flowmap painter", Its free to use. If you are artist you can do it in Photoshop.

The purpose of this flow map is to alter the water normal map.

C) Then you need to write the shader, if you are a artist you always go and buy “Flow” on unity asset store, 20$, this will do all the programming work for you.

For programmers, we need to change water normal map, so we need to take texture coordinates of the current water pixel and offset. it using the flow vector from the flow map based on time offset.

To get real effect you need to create 2 or more waves with half time cycle offset. This will create the flowing water.

```
    float2 flowmap = tex2D( FlowMapFile, texFirst ).rg * 2.0f - 1.0f;

    float waveFirst = FlowMapOffsetFirst;
    float waveSecond = FlowMapOffsetSecond;
    float3 normalFirst = tex2D(WaveMapFirst, ( texFirst * TexScale ) + flowmap * waveFirst );
    float3 normalSecond = tex2D(WaveMapSecond, ( texSecond * TexScale ) + flowmap * waveSecond );
    float flowDelta = ( abs( HalfCycle - FlowMapOffsetFirst ) / HalfCycle );
    float3 offset = lerp( normalFirst, normalSecond, flowDelta );

```

Here is the Github source code link for learning flow shaders: https://github.com/TarasOsiris/unity3d-shaders-learning/tree/master/shaders-proj/Assets/MyExperiments/FlowMaps/Shaders

D) Last not the least you will need to add Real time refraction for that you will need Unity Pro.

For water reflection and refraction follow this: https://en.wikibooks.org/wiki/Cg\_Programming/Unity/Water\_Reflection\_and\_Refraction
> 4 votes

# Answer
i dont know unity, but I normally create a model of a river, unwrap it and add a texture then offset its uv coordinates within its shader.

this might help: http://answers.unity3d.com/questions/19848/making-textures-scroll-animate-textures.html
> 1 votes

---
Tags: unity, water
---


# Question
Title: How to do offline notifications for Android in Unity3d
I am making a game for Android with Unity3d.
I've been looking for a solution to this on the web for a little, but I couldn't find anything suitable:

I want to make my game have offline notifications.
Like...I want to set up an alarm that notifies the user at some point in the future e.g.

> "Building complete!"

but the app should not have to be running.

How do I accomplish that?

# Answer
> 0 votes
Short answer: You need to create Unity Android plugin of Android project using Google Cloud Messaging. Details of how to create Android Unity plugin you can find Unity's official site.

Here are some details: A) You have to start with google Android sample app, understand the push-related API methods https://developers.google.com/cloud-messaging/android/start

B)You will need API KEY, SECRET and ANDROID SENDER ID: Project Number assigned when setting up Google Cloud Messaging.

C) Your AndroidManifest.xml. Google Cloud Messaging has some minimum API level requirements for development and testing. Set minSdkVersion property appropriately.

D) Add the following new permissions after the existing element, replacing **your\_package\_name**with the name of the app package for your project. To check the current name of your package go to File \> Build Settings \> Player Settings and select the Android tab. You will find it in the Bundle Identifier field.

```
    <permission android:name="**your_package_name**.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="**your_package_name**.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

```

E) Add the following code after the main activity inside your application tag, replacing it with the name of the app package for your project:

```
     <activity android:name="com.gamedonia.pushnotifications.GamedoniaPushHandlerActivity" />
     <receiver android:name="com.gamedonia.pushnotifications.PushBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
     <intent-filter>
     <action android:name="com.google.android.c2dm.intent.RECEIVE" />
     <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
     <category android:name="**your_package_name**" />
     </intent-filter>
     </receiver>

```

F) Use your unity functions to call methods written in your Android project, You can send push notifications from a server scripts.

---
Tags: unity, android
---


# Question
Title: JS Canvas - Creating 2D Game lighting effect like Terraria
I just started working with canvas in HTML5 and with javascript. I'm pretty satisfied with my game so far: http://xenopal.dk/game-v1.1/. But I'd like to implement lighting as well in the style of Terraria or Minecraft http://www.nerd-age.com/wp-content/uploads/2011/09/Terraria-New-Torches.png where you can have multiple light sources, even with color, without it being like realistic shadows that gets casted by the light.

I've tried to do per-pixel lighting, but that didn't go so well since it made my whole game lag like crazy and unplayable. I might have done the per-pixel lighting wrong since I'm fairly new to creating games in canvas.

I hope that you're able to help me or maybe pass on some links to other places that might be able to help. Thank you :)

// Edit - Probably forgot to mention that it should of course be a 2D lighting. I've read somewhere that even with three.js and pixi.js I might be able to create this kind of lighting, but I have no idea on how to do it.

# Answer
One way to apply light effects with the `Context2D` is to use the composite operation 'lighter' (`globalCompositeOperation`='ligther'), and adjust the alpha (`globalAlpha`= 0.0 to 1.0).
Then you can either :
• Draw the shape of the light with several geometric drawings that create a simple shade to get a cartoonish light effect.
• Define gradients to get a more realistic effect.

I did a small and simple demo here :
http://jsfiddle.net/gamealchemist/pgb3bhxj/

You can see that, by using clipping, the left (cartoonish) light does not affect the blue orb.
With a variation based on a simple sin(time) i did the a small oscillation of the light size to add a 'torch' effect.

I hope this can inspire you for your game.
Notice that you could do a multi-pass light rendering that would also darken parts of the canvas : be aware that the `'darken'` composite mode does not work on all browsers (sorry i forgot which does what), but anyway it doesn't matter because it is not required : just apply a dark (#000) fillStyle in the default ('source-over') `globalCompositeOperation` with the right `globalAlpha` and you'll darken the filled area.
> 4 votes

---
Tags: 2d, javascript, lighting, html-canvas
---


# Question
Title: Displaying whole screen image on multiple devices without stretching
In my(Android) game, all of my sprites are scaled against to a particular ratio (this 'guide' ratio stays the same regardless of the actual ratio of the screen on which they are to be displayed) - these sprites are then displayed on screens of different ratios.

This way, the game can run full screen on any device, it simply means that more/less of the game is visible on some devices than it is on others.

However, I can't work out how to diaplay a large (full-screen) image on different devices.

The only thing I can think of is to simply create the original image for the larger display and the crop it down to fit other ratios. Something like this:

So here, the image on the right is how the picture will show on the original device (full-screen with no cropping), the device on the left has a smaller width. But what if this runs on a device with a larger screen?

In this case is it simply a case of (uniformly) stretching the image until it fills the screen?

Would be grateful for some guidance.

# Answer
> 1 votes
I think you don't have to make it full screen on all devices. Nowadays most of the modern devices uses 1920x1080 ratio. So making game run on that ratio will make it run full screen more than half of the devices. And in other devices you can scale your image until one of dimensions match and center it on screen. This way there will be empty places around your image but at least all of your image will be visible.

---
Tags: graphics, aspect-ratio
---


# Question
Title: Is it possible to have a GUI in world space in Unity3D game?
I'm trying to make a tank shooter game for learning purpose and I want to have it viewed in first person, is there a way to make it so that the GUI seems projected onto the interior of the tank chamber so that I can look around without the GUI following the camera along with having the perspective change effects (i.e. the edge of the GUI further away from the camera appears smaller than the edge closer to the center of the camera)?

# Answer
Yes, You can do this in very simple way by creating 3d Text/TextMesh for the text and Quads for images.
> 1 votes

# Answer
Yes it is possible and here is the documentation
> 0 votes

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


# Question
Title: Libgdx Admob how to hide ad on specific screen?
I've recently started learning Java for android development. My first game is almost ready to publish in Google Play, but I'm affraid that google might say that on the one screen, the ad may be clicked accidentally, So I would like to hide it on that screen. The thing is, that Adview is initiated only in AndroidLuncher class in android project, but all the other classes are in core project. So what I'm asking for is a way to instruct Admob to hide when player enters GameScreen. Is that possible?

I could provide some code, but I don't know which part could help you, so I'll just post the AndroidLauncher Class onCreate method:

```
@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    config.useAccelerometer = false;
    config.useCompass = false;

    RelativeLayout layout = new RelativeLayout(this);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    // Create the libgdx View
    View gameView = initializeForView(new MainClass(), config);

    AdView AdView = new AdView(this);
    AdView.setAdSize(AdSize.SMART_BANNER);
    AdView.setAdUnitId("ca-app-pub-SECRETCODE/HERE"); //The AdUnitId
    if(isNetworkAvailable())
    {
        AdView.setBackgroundColor(Color.BLACK);
    }
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice("HERE_TOO"); //Test device
    AdView.loadAd(adRequest.build());

    layout.addView(gameView);

    // Add the AdMob view
    RelativeLayout.LayoutParams adParams =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
    adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    layout.addView(AdView, adParams);

    // Hook it all up
    setContentView(layout);

    AdView.setVisibility(View.VISIBLE);
}

```

This code works just fine, so I would prefer not to change it, as I've spent many hours getting it to work :)

# Answer
If you ask me it is not a good approach. Good news is you don't have to change too much stuff. Create an ads controller interface in your core module and implement it in your main Android class. So you can pass it to your game class and store it. Then whenever you want you can call adsController.hideBannerAd(); But you should first implement that method :D

**EDIT** tutorial for how to do it: http://www.norakomi.com/tutorial\_admob\_introduction.php#scroll\_introduction
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: How to remove this NullReferenceException in Unity
```
NullReferenceException: (null)
 UnityEditor.SerializedObject..ctor (UnityEngine.Object[] objs) (at C:/BuildAgent/work/812c4f5049264fad/Editor/MonoGenerated/Editor/SerializedPropertyBindings.cs:39)
 UnityEditor.AssetImporterInspector.GetSerializedObjectInternal () (at C:/BuildAgent/work/812c4f5049264fad/Editor/Mono/ImportSettings/AssetImporterInspector.cs:52)
 UnityEditor.Editor.get_serializedObject () (at C:/BuildAgent/work/812c4f5049264fad/Editor/MonoGenerated/Editor/EditorBindings.cs:71)
 UnityEditor.ModelImporterClipEditor.OnEnable () (at C:/BuildAgent/work/812c4f5049264fad/Editor/Mono/ImportSettings/ModelImporterClipEditor.cs:89)

```

I am getting this error, even though i dont have cs files in project.

PROBLEM FIXED - Tried reinstalling Unity at different location and project is working with any error like this. Still puzzled why this issue happened, what i should not suppose to do. Thank you all.

# Answer
> 0 votes
Try restarting Unity IDE once.

---
Tags: unity
---


title: Libgdx how to add popup interaction

text:
# Question
Title: Libgdx how to add popup interaction
I am looking for someone to point me in the right direction. I am working in libgdx. I have a game where a player will approach an object on a map and then interact with it. On interaction a new screen should come up, that then has separate interaction.

Think, lockpicking. if you walk to a door, a minigame would popup with the lock on the screen. All background art and action halts while this happens.

I was considering using an Object that triggers a Looped event that you can't escape until the condition is met EG: while(!Finished){lockpick()} then creating a render() inside lockpick()... is this a terrible idea? Should I just dump out to a different screen, and reload my game screen from saved settings? I really don't know the best way to handle this...

# Answer
> 0 votes
I would do it with Scene2d. You can have your game with a normal game loop and a SpriteBatch to manually update and draw the game and additionally you can have a Scene2d Stage that you can use to display whatever UI components you wish above your game (or below, depends on the order of calling the draw methods). It's a very nice library, great I would say, and it's relatively easy to pick up and start doing stuff. Also there are a lot of books and articles about it. Simplified it looks like this in code.

```
class MyGame extends Game {
   public SpriteBatch batch;
   public Stage stage;

   public void create() {
      batch = new SpriteBatch(.....); // construct depending on your needs
      stage = new Stage(.....); // construct depending on your needs
   }

   public void render() {
      myGame.update(delta);
      stage.act(delta);

      batch.begin();
      renderTheGame(batch);
      batch.end();

      stage.draw();
   }
}

```

The described situation is not blocking for your game - Stage does not block anything - both your game and your UI by the Stage are updated and drawn every frame. But if you want to block in case of a UI Dialog popping-up by the Stage, you can easily make an empty Game State (where the update,render method just don't do anything) and you can be in that state until the user closes the Dialog.

The benefits of using Scene2d is that it's super fast, relatively easy and it gives you a lot of things like animate the UI, skinning, 9patches, group transformations. Even if you want to write this functionality by yourself, I would recommend to look at the source of the Scene2D framework/classes, as they are very clean and well-written pieces of code.

---
Tags: 2d, libgdx
---


title: Polygons and actionlisteners Libgdx

text:
# Question
Title: Polygons and actionlisteners Libgdx
I've been browsing these forums for a while now and I nearly always am able to find an answer without having to ask my own question! Such a great community!

This is the first time I've been stumped so I hope that someone can help me, I'm just learning libgdx so any help is appreciated I know the code is rough but please be gentle as I'm learning everyday!!! :)

I'm trying to create 6 shapes with inputlisteners which eventually will return the index of the shape which will correspond to an answer, but I can only seem to get the last input listener I create to actually fire...

```
    public Panel(final int count){
    this.count = count;

    img = new Texture("badlogic.jpg");

    handlerShapeVertices = new float[]{128,30,0,256,256,256};
    handlerShape = new Polygon(handlerShapeVertices);

    triangle = new PolygonRegion(new TextureRegion(img), handlerShapeVertices,new short[]{0, 1, 2});

    triangleSprite = new PolygonSprite(triangle);

    triangleSprite.setOrigin(img.getWidth()/2,30);
    triangleSprite.setX(x);
    triangleSprite.setY(y);
    triangleSprite.setRotation(count * 60);

    handlerShape.setOrigin(triangleSprite.getOriginX(), triangleSprite.getOriginY());
    handlerShape.setPosition(x, y);
    handlerShape.rotate(count * 60);

    setBounds(x,y, 256, 256);

    addListener(new InputListener(){
        public boolean touchDown (InputEvent event, float xP, float yP, int pointer, int button) {
            //float [] temp = handlerShape.getTransformedVertices();

            if(resourceManager.getInstance().interSector.isPointInPolygon(handlerShape.getVertices(),0,6,xP,yP)) {
                System.out.println("CLICK INSIDE : " + count);
            }
            return true;
        }
    });

}

```

I figured the polygon.getTransformedVertices() should work and to check they were correct I drew them in as you can see by the white lines surrounding the polygonsprites however it doesn't seem to and none of the listeners are actually fired when I use that... I'm completely stumped and hope someone has some insight or can point me in the right direction? I don't want someone to write my code for me but a pointer would be greatly appreciated!

# Answer
I actually just figured it out, by checking all the polygons at the same time and returning the index of the polygon with the containing co-ords!

The wonders of coffee and cigarettes!!
> 1 votes

---
Tags: libgdx, sprites
---


# Question
Title: What is Vulkan and how does it differ from OpenGL?
Khronos Group (the standards body behind OpenGL) has just announced *Vulkan*:

> Vulkan is the new generation, open standard API for high-efficiency access to graphics and compute on modern GPUs. This ground-up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability.

Their page is quite marketese/jargon-heavy, as is the press release… In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.)

What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement.

---

Update: The Vulkan 1.0 spec was released on 16-02-2016.

# Answer
> 136 votes
Vulkan is a new API for hardware-accelerated graphics (and general computation) via traditional GPUs. OpenGL will continue to be developed, as it is a higher-level API than Vulkan is intended to be. Originally referred to "glNext," one can infer that Vulkan was likely going to end up being "OpenGL 5," but that the standards body eventually decided that a new name would better coincide with the relatively clean break the API purports to make from existing OpenGL paradigms.

Vulkan's *practical* advantages to game developers are primarily about control (as in, allowing more of it, potentially allowing for better optimizations at the cost of significantly more up-front work on the developer's part). Specifically:

* The API is oriented around asynchronous generation of command buffers across multiple threads and sequenced processing of those buffers to a command pipeline. This reflects the realities of modern hardware. Most high-profile and/or high-performance software built on OpenGL today implement this kind of behavior themselves; having the API support this itself means that developers need not implement and maintain that framework themselves, or that they can do so with less effort.
* Thread and memory management tasks are left to the application, not the driver, allowing game developers more control over those behaviors and thus potentially more accurate tailoring of those behaviors to their individual game's needs.
* Validation and diagnostics layers can be independently enabled, allowing in theory for better tools integration with the API (something OpenGL itself has suffered from) and disabling of excessive validation, in theory allowing "the graphics on level three" to be that much more performant.
* There's no hard API differential between mobile and desktop versions, which will in theory ease the porting of cross-platform games and if nothing else reduce version-checking headaches that everybody hates.

Vulkan's very C-like / OpenGL-like in superficial structure (the look and feel of the API calls, et cetera. It is, however, better typed (in that not everything is a bare `int`; there are relevant typedefs and so on).

It is much lower-level than OpenGL. One can expect a jump in operational setup and complexity between OpenGL and Vulkan as was seen in the D3D9 to D3D10 transition, which exposed a lot more of the under-the-cover details of GPU device operation to the API client. The transition is actually more akin to D3D11 to 12, since D3D12 is itself a very similar API to Vulkan, capability-wise.

# Answer
> 25 votes
To elaborate on OpenGL's future:

OpenGL might achieve comparable performance to Vulkan, in draw calls per second, but also regarding general driver overhead:

# Answer
> 2 votes
Khronos recently announced the release of the all-new Vulkan API, which will complement (and in some cases replace) OpenGL and OpenGL ES. Vulkan is a low-overhead API designed to bring code “closer to metal”, boosting performance and efficiency. It is based on AMD’s Mantle API, and the final spec is expected later this year.

In this post - A Brief Overview Of Vulkan API \- Toptal Technical Editor Nermin Hajdarbegovic explains why Vulkan could be a big deal in the long run. It may take a while, but this cross-platform API could drastically improve 3D performance on certain devices, especially the multi-core application processors that are used in billions of smartphones and tablets.

---
Tags: opengl, vulkan
---


title: Reflections on moving water

text:
# Question
Title: Reflections on moving water
I've been working on a simple game with semi-realistic water. I followed some tutorials to get:

* a flat water surface
* reflection and refraction (blended using fresnel term)
* ripples using a bump/normal map

Next step, I created a mesh to form actual waves. I'm animating it, and it looks great (for my intents and purposes).

Normally, to get the reflection, I would render everything on a second camera, which is actually the normal camera, but mirrored over the water plane, like in the image below:

Then, just sample that camera's output to find the reflected color. Obviously, this technique doesn't work if the water level isn't consistent. In other words, with an animated mesh, this looks terrible.

Can anybody suggest a different way to implement reflections? Or show a workaround method?

# Answer
> 1 votes
For future reference: I solved this problem by mirroring everything over the local waterheight instead of a plane. I rendered all that using the standard camera.

---
Tags: xna, water, waves
---


# Question
Title: What techniques are useful for modelling Character Actions via OOP?
I'm trying to rewrite a legacy php Browser-Based-Game so that it uses object oriented programming. I find it relatively easy to model concrete nouns, like: new Npc(), new Character(), new Account(), new Clan().

I'm finding it more difficult to model a character's actions.

For example:

* usable skills.
* a test for whether two characters are multiplayers
* attacking another character
* test for whether a character is allowed to attack another character
* etc.

Have you done something like this, and if so, what overall approach did you use to model the in-between-the-nouns behavior?

# Answer
> 1 votes
Great Question!

In general, you should start with your high level objects and then think about what they *do.* So, I'm not sure about your specific use case, but I'll assume it is the following:

> A player will use a skill to attack a different player. This will only work if that skill can be used on that player, which is dependent on a set of conditions.

In those two sentences, the nouns are "player", "skill", and "condition".

If you already have the player object, then you need to create skill and condition. Then, you need to have player possess a set of skills and a skill posses a set of conditions. Let's start with conditions:

```
interface condition {
    public function isOk(Player $otherPlayer);
}

```

Then, you can make any condition you want, let's say the one that checks if the player has a shield:

```
class hasShield implements condition {
    public function isOk(Player $otherPlayer) {
        return !$otherPlayer.hasShield;
    }
}

```

Now onto skills, skills will need a way to attack another player, so an interface could be:

```
interface skill {
    public function attack(Player $otherPlayer);
}

```

Then, you could create any skill you wanted, and have it fit this interface:

```
class basicAttack implements skill {

    public function attack(Player $otherPlayer) {
        // check conditions
        foreach ($conditions as $condition) {
           if (! $condtion.isOk($otherPlayer) return;
        }

        // attack
        // do thing to $otherPlayer;
    }

}

```

Finally, you need to add a list of skills in the player object and provide a way for that class to choose and use one of those skills to attack another player.

Hope this helps!

---
Tags: browser-based-games, php, oop
---


title: how to generate road in racing game

text:
# Question
Title: how to generate road in racing game
I'm making a racing game in python and I kind of wrote myself into a corner. This for loop:

```
 for i in objects:
     if i.name == "road":
         if i.y == 0:
             road = Road(road_x,-20,road_width,20)
             objects.append(road)

```

is how I generate new road tiles as the old ones move down the screen. When a block spawns 20 pixels offscreen, it falls down until its top left corner hits 0 and then a new block spawns above it. if you run this code: https://github.com/hailfire006/economy\_game/blob/master/racing%20game you can see that it works great, right up until the player accelerates by pressing up or "w", at which point the road stops spawning.

What I think is happening is that the road is skipping the 0 mark and that's why no new road is spawning, but increasing the acceleration in the code doesn't seem to mess it up, it's only when it's changed dynamically in game. Can soneone explain what's happening here because nothing I try is working and I've been stuck on this for days...

# Answer
> 0 votes
You're currently checking if `i.y == 0` and only creating the new road section if this is true. If you accelerate and the roads stop lining up perfectly with the bounds of the world, this statement will never be true because the y value will jump from positive to negative without hitting exactly zero. Try `i.y<=0`; this way, even if the road stops lining up perfectly, you will still create new road tiles when one goes off screen.

Keep in mind, though, that if you create the road tiles at a set position, there will be unsightly spaces in between tiles when you accelerate. To remedy this, create the new tile a set y-distance away from the deleted tile.

---
Tags: procedural-generation, python, pygame, racing
---


# Question
Title: How to check distance between two different vectors?
So I have a very basic racing game, where I would like the car to stop once it hits the finish line. Respectively when the distance between the car and the finish line hits or goes under 0 the car stops, but instead of stopping it continues to go on. How can I fix this?

Here's my code:

```
    public float speed = 0f;
    public float gravity = 0f;
    public Transform finishline;
    public Transform car;
    public Transform finish;

    void CarMove ()
    {
        if (Vector2.Distance (finishline.position, car.position) != 0)
        {
            if ( Input.GetKey(KeyCode.RightArrow))
            {
                transform.Translate(Vector2.right * speed * Time.deltaTime);
            }

            else
            {
                return;
            }
        }
    }

    // Update is called once per frame
    void Update ()
    {
        CarMove();
    }
}

```

# Answer
The problem your having is that motion in games, as smooth as it might look, is better seen as a series of short teleportations. So, since distance is an unsigned value (always greater than zero), your car is just teleporting right past the absolute distance of zero. That causes the check to never go off.

You have 3 options:

1. You can add a margin of error (eg. `if (distance < 0.2f)` instead of `d != 0`) But this can be a problem because if the car is moving too fast, or is too far to the left of your finish lines "point", then it still teleports past.
2. You can scrap the idea of measuring distance all together, taking advantage of Unity's `OnTriggerEnter` functionality to filter out the finish line/checkpoints and determine the cars victory or place. That would allow you to add in checkpoints or finish line's simply by dragging a prefab from the editor (it's always nice to have that mobility)

Fun Note: This rout should also be more stable because of sweep collision testing. Most game engines, before they teleport an object from point A to point B, do a sort of collision test that checks for collisions with objects between the points A and B. While your standard functions are only called *at* point A or B for performance reasons, the `OnTriggerEnter` will be called even if the object is just teleported to the other side.
3. Rather than keeping track of the distance, try keeping track of how it's changing. If you're getting closer and closer, and then suddenly getting farther and farther, then you probably crossed the finish line. This can lead to a false positive though. A 360 degree turn for example, would trigger this.
> 3 votes

# Answer
This wouldn't answer the question of measuring the distance but for the scenario that you described, I find that placing a collider as trigger on the finish line and checking OnTriggerEnter in your car would be a better solution rather than calculating the distance.

For distance check, Dexyne is totally correct but you could also check using the `sqrMagnitude` which yield better performance.

You would do a check like that `(finishline.position - car.position).sqrMagnitude < Mathf.Epsilon`
> 1 votes

# Answer
Augment your finish line point with a direction vector representing the "forward" direction. Then, instead of:

```
if (Vector2.Distance (finishline.position, car.position) != 0)
[...]

```

Do:

```
if (Vector2.Dot(car.position - finishline.position, finishline.direction) > 0)
[...]

```

Note, if the direction happens to be aligned to a cartesian axis, say +X, the above is equivalent to:

```
if (car.position.X - finishline.position.X > 0)
[...]

```
> 1 votes

# Answer
**Update** – My bad, as @DMGregory says **the value of a distance cannot be negative** (and it makes sense). As @Kimserey and I says, you can use a trigger. Probably better in this case and easier to use.

---

> when the distance between the car and the finish line hits or goes under 0

I think the problem is your if statement.

Your test should be:

```
if (Vector2.Distance (finishline.position, car.position) <= 0)

```

and not `if (Vector2.Distance (finishline.position, car.position) != 0)` as a vector can be negative.

Note: You can also use a trigger collider on the finishing line and set the car speed to 0 when it hit the finishing line.
> -1 votes

---
Tags: c#, unity, vector, unityscript, racing
---


# Question
Title: Sprite animation frames in Adobe Photoshop CC
I am creating 64x64 px sprites for my game and want to test the animation play before saving the sprite sheet in game.

I watched this video to learn, which told me:

1) Click Window-\>Timeframe

2) Add selected Frame

3) Click duplicate frame, then Tween frames in between. These icons on the bottom left of timeline:

The issue is, he doesn't show how to do it if my sprite needs to animate in place... only if it moves across a canvas as such:

My game uses Texture Packer to pack individual 64x64px images and then renders the frames. Therefore, I need to make little adjustments to the single frame in place, and animate them:

I tried selecting my next frame layer for my sprite and duplicating it, but it only ends up duplicating the first frame.

How can I add my selected layer in my Layers to the timeline?

# Answer
You will have to manually add all the frames for your animation. You don't need tweening unless you want to rotate or move the sprite from point A to B and have it automagically interpolate (be)'tween the key frames.

For walking, jumping, shooting animations, etc. You have to do it manually. There's no magic for that.

Here is a little guide to help you with how to use the timeline:

https://helpx.adobe.com/photoshop/using/creating-frame-animations.html
> 2 votes

---
Tags: animation, rpg
---


title: How to script enable VR in Unity 5.1

text:
# Question
Title: How to script enable VR in Unity 5.1
Unity 5.1 has integrated VR, its in the Build Player Settings as a checkbox. I want a startup scene that is not VR, then when the user starts it enables the VR camera. Can I do that?

# Answer
> To enable VR for your game builds and the editor, set the “Virtual Reality Supported” option in Player Settings.

This means you can activate it via the PlayerSettings either via the UI or via Script.

```
PlayerSettings.virtualRealitySupported = true;

```

Unity wrote a manual about VR in general. http://docs.unity3d.com/Manual/VROverview.html
> 3 votes

---
Tags: virtual-reality, unity
---


# Question
Title: Projectile Rotation During Flight (Tank Game)
I have a tank firing projectiles into the air.

I want the projectiles to be rotated relative to their position along their flight path.

See the diagram I drew in the image below.

At any given point I know the x and y of the projectile, z represents initial velocity, theta is also known.

# Answer
> 3 votes
Your problem is not that tricky : you do have a formula that will give you the next position (at `t+dt`), given the current one.
Now say the projectile is at `P` : use the formula to get the next point `NP` : `D = (NP-P)` is the direction vector at t.

Now depending on what you seek :
• Angle ? Get the angle (atan2) of this D vector, to have the angle of your projectile.

```
angle = atan2 ( ( D.y), (D.x) ) ;

```

• Vector ? Normalize the Direction vector to have the normalized direction of your missile.

```
dLength = sqrt( sq(D.x) + sq(D.y) ) ;
D.x /= dLength;
D.y /= dLength;

```

(Rq : normalized means it has a length of one.
So if `P` is the rear of the missile, and `D` is the normalized direction, missile's head is at `P + missileLength * D` );

( Another remark : from your post it seems that you do not compute the velocity vector. But if you do, the missile direction is this very velocity vector, just take its angle or normalize it to get what you want. )

# Answer
> 0 votes
if you now x and y at any given point then localy derivate in respect of time.

Let x,y be current position at current time, let x1 and y1 be position at current time - small delta , then compute the slope as

m = (y-y1) / (x-x0)

beware subdivision by zero (x = x0 means proiectile perpendicular)

For the rotation angle given y-y1 and x-x1 you can enjoy some trigonometry :

# Answer
> 0 votes
it is very simple, somehow you have some kind of speed right ? i mean on each update you add some kind of velocity to x and y so they can move to their target?
now
you have your bullet x and y
and you have the velocity that must be added each update
before you add the velocity
say

```
bullet.rotation = atan2(velocity.y, velocity.x);

```

this should solve your problem (note that depending on your application you might want to convert degree to radius or the opposite)
hope that helps

---
Tags: rotation, trajectory
---


# Question
Title: Calculating pitch angle to hit a target using a projectile that has fixed speed
I am trying to calculate a vertical angle needed to hit a target at `[distance, elevation]` 2D coordinates relative to shooter given a fixed projectile velocity, air drag and gravitational acceleration.

Although I operate in 3D world (minecraft) the task itself eliminates the 3D problem. Once you calculate the rotation around your axis, which is in my case just `atan2(-x3D, -z3D)` what I'm solving is described on this picture:

From a wikipedia article about balistics I have picked this equation. As you can see, it seems to directly solve for my angle:

$$ \theta = arctan \bigg( \frac{v^2 \pm \sqrt{v^4-g(gx^2+2yv^2)}}{gx} \bigg) $$

So I rewrote the equation in javascript as `Math.atan((v*v+Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x);` where `v` is speed, `g` is gravitational acceleration, `x` is distance and `y` is elevation of the target.

I implemented the whole algorithm as following:

```
//Assumed constants
var g = 9.81;  //Gravitational acceleration
var v = 35.9;  //Experimantally measured arrow speed
//The point of player head 3D [x,y,z]
var mepoint = this.bot.entity.position.offset(0, this.bot.entity.height, 0);
//The point of the target center assuming we're at [0, 0, 0] again using 3D [x,y,z]
var point = this.target.position.offset(0, this.target.height/2, 0).minus(mepoint);
//Transfer the coordinates with regards to the bot rotation
//That is, the 2D X coordinate is the distance as seen from the top
var x = Math.sqrt(point.x*point.x+point.z*point.z);
//The 2D Y coordinate is just plain difference between elevation
var y = point.y;
console.log("|BOT: TaskShoot| Target 2D coords [distance, elevation]: ",[x, y]);
//Calculate the horizontal angle - look at the target 3D [x,z] coordinates
var yaw = Math.atan2(-point.x, -point.z);

//Calculate the pitch using the equation from wikipedia
var pitch =  Math.atan((v*v+Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x);
//Since it has 2 solutions, solve for bot + and - variant
var pitch2 = Math.atan((v*v-Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/g*x);
console.log("|BOT: TaskShoot| Angles: ",[pitch, pitch2]);
//NaN test: !(NaN>=0 || NaN<=0)
//Test two pitches and avoid NaNs. If both pitches are NaN, the target is out of range.
if(!isNaN(pitch))
  this.bot.look(yaw, pitch, false, function() {_this.finished();});
else if(!isNaN(pitch2))
  this.bot.look(yaw, pitch2, false, function() {_this.finished();});
else
  this.bot.look(yaw, 0, false, function() {_this.finishedError(123, "Couldn't calculate aim pitch - out of range? Aiming straight.");});

```

But this calculation allways returns almost the same values for the angles:

```
|BOT: TaskShoot| Target 2D coords [distance, elevation]:  [ 13.027689861406742, 3.032749999999993 ]
|BOT: TaskShoot| Angles:  [ 1.5704302724148764, -1.5643119398157057 ]

```

`1.5704` is about `pi/2`. I never got significantly different result than this. So what's wrong with my calculation and how should I fix it? Did I even pick the right formula?

# Answer
> 1 votes
Refactoring is your friend !!!
Separate the issues and try to get your code as generic as possible.
Separate and factorise the steps of the computing.
Keep comments short.

• Boilerplate :

```
// ------------------------

var g = 9.81; //Gravitational acceleration
var v = 35.9; //Experimantally measured arrow speed

var sqrt = Math.sqrt,
    atan2 = Math.atan2,
    abs = Math.abs,
    sq = function (x) {
        return x * x;
    };

```

• Function dealing with entities

```
// ------------------------

function getAngleToEntity(srcEntity, tgtEntity) {
    return getAngleTo(
    srcEntity.position.offset(0, srcEntity.height / 2, 0),
    tgtEntity.position.offset(0, srcEntity.height / 2, 0),
    v);
}

```

• Function just dealing with vectors/point

```
// ------------------------

function getAngleTo(srcPoint, dstPoint, speed) {
    // delta = dst - src
    var delta = dstPoint.minus(srcPoint);
    // distance as seen from the top
    var x = Math.sqrt(sq(delta.x) + sq(delta.z));
    // elevation
    var y = delta.y;
    //Calculate the direct angle
    var straight = Math.atan2(y, x);
    //Calculate the pitch using the equation from wikipedia
    var sqSpeed = sq(speed),
        qdSpeed = sq(sqSpeed);
    var rightTerm = qdSpeed - g * (g * sq(x) + 2 * sq(y));
    if (rightTerm < 0) {
        // handle not-able-to-reach case
        console.log('no reach');
        // return ... ??? ;
    }
    rightTerm = sqrt(rightTerm);
    var angle1 = atan2((sqSpeed + rightTerm), (g * x));
    var angle2 = atan2((sqSpeed - rightTerm), (g * x));
    // Choose the angle closest from straight angle.
    var resAngle = abs(angle1 - straight) < abs(angle2 - straight) ? angle1 : angle2;
    // log
    console.log("|BOT: TaskShoot| Target 2D coords [distance, elevation]: ", [x, y]);
    console.log("|BOT: TaskShoot| Angles: ", [angle1, angle2]);
    //
    return resAngle;
}

```

• Unit tests (add some others, and check results !! ) :

```
// ------------------------

function Vector(x, y, z) { this.x = x;
    this.y = y;
    this.z = z;
    this.minus = function (other) {
        return new Vector(this.x - other.x, this.y - other.y, this.z - other.z);
    }
}

// ------------------------

// some unit tests here
getAngleTo(new Vector(0, 0, 0), new Vector(30, 0, 90), v);

```

# Answer
> 0 votes
Try fixing parenthesis:

```
var pitch =  Math.atan((v*v+Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/(g*x));
var pitch2 = Math.atan((v*v-Math.sqrt(v*v*v*v - g*(g*x*x+2*y*v*v)))/(g*x));

```

Consider also using atan2 function. Maybe in your case it won't fix anything but it's always good to know about it. https://en.wikipedia.org/wiki/Atan2

---
Tags: mathematics, javascript, ai, minecraft-modding, aiming
---


title: Collision in EdgeCollider Unity

text:
# Question
Title: Collision in EdgeCollider Unity
I want to make a collider for a line that I've drawn on the screen using mouse. so the detection should be cover the whole line that has drawn.

What I've learned from edge collider is you can have collider if you assign the position of a certain point in col.transform.position (for example I can assign the startpos of my line and the collider works only for that point).

the green line which is drawn by mouse in front of car is using the LineRenderer and requires EdgeCollider to be a road that car can drive on it's surface

and my functions:

```
private LineRenderer line; // Reference to LineRenderer
private Vector3 mousePos;
private Vector3 startPos;   // Start position of line
private Vector3 endPos; // End position of line
public Material material;

void Update()
{
    // On mouse down new line will be created
    if (Input.GetMouseButtonDown(0))
    {
        if (line == null)
        {
            createLine();
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(0, mousePos);
            startPos = mousePos;
        }
    }
    else if (Input.GetMouseButtonUp(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(1, mousePos);
            endPos = mousePos;
            addColliderToLine();
            line = null;
        }
    }
    else if (Input.GetMouseButton(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            line.SetPosition(1, mousePos);
        }
    }
}
// Following method creates line runtime using Line Renderer component
private void createLine()
{
    line = new GameObject("Line").AddComponent<LineRenderer>();
    line.material = material;
    line.SetVertexCount(2);
    line.SetWidth(1.1f, 1.1f);
    line.SetColors(Color.black, Color.black);
    line.useWorldSpace = true;
}
// Following method adds collider to created line
private void addColliderToLine()
{
    EdgeCollider2D col = new GameObject("Collider").AddComponent<EdgeCollider2D>();
    col.transform.parent = line.transform; // Collider is added as child object of line

    col.points[0] = startPos;
    col.points[1] = endPos;

    Vector3 midPoint = (startPos + endPos) / 2;
    col.transform.position = midPoint; // setting position of collider object
    // Following lines calculate the angle between startPos and endPos
    float angle = (Mathf.Abs(startPos.y - endPos.y) / Mathf.Abs(startPos.x - endPos.x));
    if ((startPos.y < endPos.y && startPos.x > endPos.x) || (endPos.y < startPos.y && endPos.x > startPos.x))
    {
        angle *= -1;
    }
    angle = Mathf.Rad2Deg * Mathf.Atan(angle);
    col.transform.Rotate(0, 0, angle);
}

```

btw i don't know what that col.points\[\] used for. I just found it from the unity documentation which won't make any collision

# Answer
The problem with the collision was that the edge collider points were not being set properly. Instead of setting individual points you actually need to supply Vector2 array of two elements. This is always the case in C# , in javascript it works fine. As the start and end points were not set , the collider was taking default 0.5 co ordinates.

You can see in the attached image that the collider is not covering the whole line.

So following are the changes done to the original code.

```
private LineRenderer line; // Reference to LineRenderer
private Vector3 mousePos;
private Vector3 startPos;   // Start position of line
private Vector3 endPos; // End position of line
public Material material;

void Update()
{
    // On mouse down new line will be created
    if (Input.GetMouseButtonDown(0))
    {
        if (line == null)
        {
            createLine();
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            Debug.Log("mouse pos "+mousePos);
            line.SetPosition(0, mousePos);
            startPos = mousePos;
        }
    }
    else if (Input.GetMouseButtonUp(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            Debug.Log("mouse pos "+mousePos);

            line.SetPosition(1, mousePos);

            endPos = mousePos;
            addColliderToLine();
            line = null;
        }
    }
    else if (Input.GetMouseButton(0))
    {
        if (line)
        {
            mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            mousePos.z = 0;
            Debug.Log("mouse pos "+mousePos);
            line.SetPosition(1, mousePos);
        }
    }
}

// Following method creates line runtime using Line Renderer component

private void createLine()
{
    line = new GameObject("Line").AddComponent<LineRenderer>();
    line.material = material;
    line.SetVertexCount(2);
    line.SetWidth(1.1f, 1.1f);
    line.SetColors(Color.black, Color.black);
    line.useWorldSpace = true;
}

// Following method adds collider to created line

private void addColliderToLine()
{
    EdgeCollider2D col = new GameObject("Collider").AddComponent<EdgeCollider2D>();

// Collider is added as child object of line
    col.transform.parent = line.transform;

    Vector2[] pointsArray = new Vector2[]{new Vector2(startPos.x,startPos.y),new Vector2(endPos.x,endPos.y)};

    col.points = pointsArray;

    Debug.LogWarning("mos pos "+col.points[0]+" end pos "+col.points[0] );

}

```

This rectifies the collider points and you can see that now it covers the whole line :)
> 0 votes

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


# Question
Title: Unity how to change material properties at runtime
I'm working on a unity game where I want to change the color of a material from within a script. The material applies to a line renderer.

I currently have the following script:

```
using UnityEngine;
using System.Collections;

public class LaserProperties : MonoBehaviour {
    public Vector3 RGBStrengths;
    public LineRenderer lineRenderer;

    /*
     * returns the color in RGB.
     */
    Color getColor(){
        Color c = new Color (0, 0, 0, 1);
        float highest = Mathf.Max (RGBStrengths.x, RGBStrengths.y, RGBStrengths.z);
        c.r = RGBStrengths.x / highest;
        c.g = RGBStrengths.y / highest;
        c.b = RGBStrengths.z / highest;
        return c;
    }
    /*
     * returns the total amount of energy in the beam
     */
    float getStrength(){
        return RGBStrengths.magnitude;
    }
    void Update(){
        updateBeam ();
        Debug.Log (getColor());
    }
    /*
     * set color of the beam to the color of the laser
     */
    public void updateBeam(){
        lineRenderer.SetWidth (getStrength (), getStrength());
        lineRenderer.material.color = getColor ();
        lineRenderer.material.SetColor ("_Albedo", getColor ());
        lineRenderer.material.SetColor ("_Emission", getColor ());

    }
}

```

And here is the material .

However changing the properties does not result in any chance to the material in question.

Any idea what I'm doing wrong?

# Answer
I tested your script and was able to dynamically adjust the colors of the line renderer. Perhaps you didn't pass your linerenderer component into your script in the editor on the attached object? Alternatively, you could add to your script:

```
void Start() {
    lineRenderer = gameObject.GetComponent<LineRenderer>();
}

```

Aside from that your code seems to work fine.
> 2 votes

# Answer
When using Unity 5 and the Standard shader you need to use `"_EmissionColor"` rather than `"_Emission"` to set the Emission value.
> 0 votes

---
Tags: c#, unity, shaders, graphics, materials
---


title: XNA 2D rotation Matrix offset/origin

text:
# Question
Title: XNA 2D rotation Matrix offset/origin
I'm currently struggling with finding the offset for my original camera translation after I have applied a rotation for it.

```
transform = Matrix.CreateScale(new Vector3(1, 0.75f, 1))
            * Matrix.CreateTranslation(-playerpos.X+dash, -playerpos.Y, 1);

rotation = Matrix.CreateRotationX(MathHelper.ToRadians(valuex))
            * Matrix.CreateRotationY(MathHelper.ToRadians(valuey));

transform2 = rotation
            * Matrix.CreateScale(new Vector3(1, 0.75f, 0))
            * Matrix.CreateTranslation(-playerpos.X + dash, -playerpos.Y, 0);

```

My original transform matrix is for the camera that follows the player, I use transform2 for sprites I want to rotate.

```
spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
                   null, null, null, camera.transform);

spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, null,
                   null, null, null, camera.transform2);

```

Edit:

```
for (int i = 0; i < 3; i++)
{
  spriteBatch.Draw( world.mcircle[i],
                    new Vector2(5320, 1200),
                    null,
                    Color.White,
                    (world.finishtime * 5) / (i + 1),
                    new Vector2(50, 50),
                    3f,
                    SpriteEffects.None,
                    0);
}

```

So I pass two different transformations based on whether I want stuff to rotate or not.

But I just can't seem to find the correct offset in position for the rotated sprites, they seem to gravitate towards (0, 0)? as the rotational value increases.

I'd be really glad if someone could help me out with this.

Edit: I think I'd only need a proper origin for the sprite position, because currently it goes towards (0, 0) and I'm unsure how to incorporate one in this state.

Edit:

Tried several origin points for transform2, but when I input the object's coordinates as source, it just displaces it by that amount, and when I set the object's position to (0,0) it still has the same effect as if having the original origin point.

```
transform2 = Matrix.CreateTranslation(0, 0, 0)
             * (rotation * Matrix.CreateScale(new Vector3(1, 0.75f, 0))
             * Matrix.CreateTranslation((-playerpos.X + dash), -playerpos.Y, 0)); //just an example currently

```

# Answer
Okay so the answer was rather simple, should've thought about it earlier, in order to give a correct origin you'll need to get the world coordinates for it through your original view matrix's transformation.

```
transform2 =
Matrix.CreateTranslation(0, 0, 0)
* (rotation * Matrix.CreateScale(new Vector3(1, 0.75f, 0))
* Matrix.CreateTranslation(Vector2.Transform(new Vector2(5320, 1200), transform).X, Vector2.Transform(new Vector2(5320, 1200), transform).Y, 0));

```

The vector2 (5320,1200) is just an example that I wanted my object at.
> 0 votes

---
Tags: xna, 2d, rotation, matrix, spritebatch
---


title: Making Save and Load Windows using SDL

text:
# Question
Title: Making Save and Load Windows using SDL
I've been working on a world builder project recently and I've finished most of the work but there is just one thing I can't think of how to do.

For example in a strategy game's world builder when you want to save a map and click the save button a window pops up and you can enter a name you want and save the map with that name, or overwrite a map you can chose by clicking one of the pre-saved maps in the list in the window. Or load a map again by clicking a map name in a load window.

How can I render a text while I'm writing it with SDL 2.0.3(when you're saving a map you need to see the name you give) and save that file with that name and also show other save files' names in a list?Is there a way to do it with SDL\_ttf library or should I use bitmapfonts?

How can I decide if I want to overwrite a map or create a new one (I need to overwrite a map when it's name is clicked and create a new one when the bar to write the new map's name is clicked)?

In the load menu how can I load the specific save file I've chosen?

And just one more question: I'm currently writing the save data in a .txt file, is there a better way of doing that that you suggest?

I'm using SDL with C++.

Thanks.

# Answer
SDL doesn't provide typical App GUI affordances.

(It *does* have `SDL_ShowSimpleMessageBox()` and `SDL_ShowMessageBox()` which are probably only useful for reporting a startup error or a crash, or system advisories.)

You could either mix-in some platform-specific bits as @wondra suggests (quick and done!), or use an abstraction layer which caters more specifically to higher level application work, such as Juce, Qt, or wxwidget.

https://stackoverflow.com/questions/6145910/cross-platform-native-open-save-file-dialogs

Or roll your own on top of OpenGL; chances are you've done some of that already for other GUI elements in your game/editor. Text entry & display is a little harder than a button, but still, just more of the same.

https://stackoverflow.com/questions/5289447/using-sdl-ttf-with-opengl discusses how to render text with a ttf font onto an SDL\_Surface, which you can then put onto your window. (There's many other ways to render text, that's just one approach.)

(As for the P.S. question, sure, text files are great, you can read & edit them. Win!)
> 1 votes

# Answer
If you don't use OpenGl library that does not implement open/save file dialog, you can avoid a lot of work(rendering text, folder browsing etc.) by using platform-specific code as your editor will likely run on single system anyway. Just ask you OS do it - quick, "cheap" and easy. Similar question was answered here for linux.
> 2 votes

---
Tags: c++, game-design, sdl2
---


# Question
Title: How do I get the position and rotation of an animated object in Unity?
I have this object which is being animated, the animation moves a arm and hand. I want it to look like it's holding something but I can't move the object to the hand because even though the animation appears to move the world position of the animation object stays the same, the objects parent is the hand but it's still not moving to it. So how do I move the object to the animations hand while it's being animated in unity?

Maybe this could help to visualize what my problem is:

I found another way around the problem: attached the object as a child of the bone instead of the hand mesh. I still don't know why it didn't move with the hand.

# Answer
In order for it to work you have to parent the bat to the bone and not to the hand. In that way it will move with it and follow all the animations of the bone.
> 1 votes

# Answer
If your problem is that the model is animated but the object is not, then you have to make the object a child of the arm, so that when the arm moves, the position and rotation of that object depends on the transform of the arm.
> 0 votes

# Answer
It's very difficult to move an object independently to match an animation. The standard method is to attach the object to the skeleton of the mesh.

Otherwise, you would need know the precise dimensions of both meshes (character/hand and object) and the movements of the animation at every frame if you want it to look right, which can be pretty resource heavy.

Alternately you would need to do some rather complex computations based on the key-frames of the animation and you would still need to know the precise dimensions of the mesh. You don't want to have to rely on 'magic numbers' like mesh dimension or else when you change the mesh, you need to change your code too and that is bad practice in programming. This is also rather computationally expensive for little gain, especially if you are trying to get the dimensions of the mesh on the fly.

The animator handles all of this complexity for you if you attach your object to the skeleton. Though not perfect, it will almost always be good enough. Your attached object may still penetrate the mesh at some points, since the animator doesn't track the dimensions of the mesh either, just the skeleton.

You might get more accuracy if you animate the object separately from the character mesh so you can make slight adjustments in your object animation to account for variances in how the object should move compared to the hand, but that is usually overkill and that kind of accuracy is rarely needed in a game.
> 0 votes

---
Tags: unity
---