Friday, March 31, 2017

Programming Weapon Sway

Weapon sway in games can easily be taken for granted by players. However, when it's not implemented the game looks plain and undone with a stationary weapon in the first person view. So that begs the question, how do first person shooters implement that cool weapon sway?! The truth is it's quite simple and this post will provide a brief code snippet on how to do it. Keep in mind that there are 1000 ways to skin a cat and the technique I'm presenting is one of those ways..but it is fairly popular.

Let's talk about Lissajous curves. There are plenty of websites that go into great detail about all the history, equations, and cool stuff you can do with Lissajous curves. I'll explain it simply and in terms of weapon sway. Think in your mind of your favorite FPS. As you walk the weapon typically sways horizontally and vertically in nice harmonic pattern. This complex motion in the x and y dimension is a Lissajous pattern.

Now, to program sway via Lissajous curves you can simply combine sin and/or cosine waves. There are different forms of the equations that use sin and/or cosine waves but for our example we will use 2 sin waves. Basically the goal is to oscillate vertically and horizontally harmoniously. From there you can customize your waves to get the effect you want.

This code will get you that traditional figure eight sway (this is a Unity C# snippet). Enjoy!

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

public class SimpleWeaponSway : MonoBehaviour 
{

    [SerializeField]
    Transform weapon;

    [Range(01f)]
    [SerializeField]
    float verticalSwayAmount = 0.5f;

    [Range(01f)]
    [SerializeField]
    float horiztonalSwayAmount = 1f;

    [Range(015f)]
    [SerializeField]
    float swaySpeed = 4f;

    // Update is called once per frame
    void Update () 
    {
        float x = 0, y = 0;
        y += verticalSwayAmount * Mathf.Sin((swaySpeed * 2) * Time.time);
        x += horiztonalSwayAmount * Mathf.Sin(swaySpeed * Time.time);        
        weapon.position = new Vector3(xyweapon.position.z);
    }
}

Monday, March 13, 2017

WebAPI Using Entity Framework Core and Postgres in Visual Studio Code

It seems like Visual Studio Code is really starting to get some traction so I finally decided to bite the bullet and see what all the buzz is about. I set out a goal of putting together a webapi that would incorperate Entity Framework Core and Postgres. This seemed like this was a good route because there was some confusing/lacking information I came across when trying to put this project together. So hopefully in this blog post I can give you folks a nice, clean, and easy to understand guide to putting this stuff together.

I do recommend that the audience for this has some knowledge Entity Framework, database drivers, etc. I'm not going into great detail in this post about that stuff - it's more for just project setup. Regardless this will get you generating a code first databases! Enjoy.

Here goes...


My Environment
I've ran through this process on a Windows 7 desktop and a Mac bootcamping Windows 10

Software requirements






.Net Core SDK 1.1.1
Download the .exe download and use the default install options
https://www.microsoft.com/net/download/core





Visual Studio Code 1.10.2 
Downloaded the installer for windows and used all the default install options.
https://code.visualstudio.com/Download


Visual Studio Code Extensions


Navigate to the extension tab in VSCode, or use the shortcut  Ctrl+Shift+X, and install:  C#, C# Extensions, C# XML Documentation Comments, and Code Runner



PostgreSql 9.6.2
Download and run the installer, default settings are fine, you will be prompted to enter your superuser password.

Creating the Project

First create a folder in a spot on your machine where you want your project to live. I'm going to put mine on my desktop.
Example Path: C:\Users\Adam\Desktop\MyProject


Open Windows PowerShell and navigate to the folder you created

Execute the command: dotnet new

Then execute the command: dotnet new webapi

Finally execute:  code .
This will open your project in VSCode

Adding NuGet Packages

Open your terminal (Ctrl+`)
Execute the following commands
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package NpgSql.EntityFrameworkCore.PostgreSQL
dotnet add package NpgSql.EntityFrameworkCore.PostgreSQL.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet



You will need to add the <ItemGroup> for tools and add the reference to the Entity Framework Tools to your csproj file. The file should reflect the image above


Create Your Database




Open PgAdmin 4
In the Create-Server Dialog enter a server name in the General tab, I chose "MyProject". In the Connection tab you can enter localhost for the hostname and type a password of your choice. For this example my password will be password. You can leave the other fields as their default values.


Create DbContext and Model



In VSCode create a file  called dbContext.cs. File contents:

using Microsoft.EntityFrameworkCore;
using MyProject.Models;

namespace MyProject
{
    public class MyProjectDbContext : DbContext
    {
        public DbSet<Person> People { getset; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Username=postgres;Password=password;Database=MyProject;");
        }
    }
}

In VSCode create a Models Folder in the root of your project. Inside of the Models folder create a Person.cs. File contents:

namespace MyProject.Models
{
    public class Person
    {
        public int PersonId { getset; }
        public string Name { getset; }
    }
}


Adding Migration and Updating Database


It's finally time to add your migration and update your database. We are going to call our migration "initial" but you can call it whatever you like.
In the VSCode terminal execute the command: dotnet ef migrations add initial
This should have generated some files under a new folder in your project called Migrations



Lastly to update the database execute the command: dotnet ef database update
Your database should now be updated in PgAdmin. You may have to refresh the database to see the changes.


That's it, thank you very much for reading. Please comment if you run into any issues I might be able to help with!

Saturday, August 8, 2015

YummyNet (C# Networking)

This is an old post migrated from my previous blog (08/08/2015). I apologize if any info seems outdated.

I’m working on a personal game project (I plan to talk more about in a future post) that required some networking. I wanted to use TCP protocol for reliability and wanted to explore managed networking so I went with a C# async socket implementation. I’m going to include the client/server dlls and I’ll soon update with an example of implementing! If you use this code please be sure to give credit where credit is due!
Click the link below for the libs:
EDIT:
Download the link below for a simple example of implementation.

Sunday, September 22, 2013

Project Xeno


This is an old post migrated from my previous blog (09/22/2013). I apologize if any info seems outdated.

Project Xeno is the latest Unity project I’ve been working on. It’s still in development but I really wanted to get some early screen shots of our progress so far. This game is an arcade style beat ‘em up/brawler. So far I’ve done all the gameplay and AI programming. Xeno (the protagonist) is able to engage in armed and unarmed melee combat with the ability to wield and dual-wield several different weapons. Xeno is capable of several different attack types including combo attacks, dash attacks, charged attacks, and aerial attacks. Weapons available include one-handed swords, two-handed swords, hammers, kamas, scythes, kunais, sai, daggers, lance, spear, staff, axes, and more. Here are some screenshots of the game thus far (below).


The cool art in this game was contributed by Jonathan Shook. Jon’s site:






Wednesday, August 21, 2013

Intro to Unity - Basic Platformer

This is an old post migrated from my previous blog (08/21/2013). I apologize if any info seems outdated.

Here is a simple platformer game I put together to teach people how to make a basic game in Unity for workshops presented at Microsoft in Alphretta, GA. Here is a link to download: Basic_Platformer
Please feel free to help yourself to the code I have provided in this starter kit. If you have any questions please contact me.

Monday, October 1, 2012

Fog of War

This is an old post migrated from my previous blog (10/01/2012). I apologize if any info seems outdated.

Many RTS games have a fog of war system. I want to share a portion of code that I used to accomplish this in Unity for the MOBA Project. I used a fairly basic approach and there are certainly more elegant ways to accomplish this. I will be showing how to calculated the pixel of intersection of a plane that is the fog of war.
First, I created the fog by placing a plane over the entire level. The plane has a dark translucent material in order to look something like fog. Then the idea is that; when a player or unit is between the fog and the camera, an area in the texture would be alphaed    out exposing that portion of the map.
To figure out the point in the texture between the unit/player and the camera I used a raytrace. Be sure to set up a mask, that way you only are casting against the plane that is the fog of war.
LayerMask mask = LayerMask.NameToLayer("FogOfWar");
RaycastHit hit;
mask=~mask;
if(Physics.Raycast(ray, out hit, dist, mask.value))
{//calc intersect pixel here}
Pixel data is stored as a 1D array. Only the texture coordinate information from the Raycast is available. What is important to is the actual pixel where the ray intersects with the fog of war plane. The code below is how to calculate that pixel from texture coordinate information.
if(hit.collider == null)
return;
Texture2D tex = hit.collider.renderer.material.mainTexture as Texture2D;
if(tex == null)
return;
int row = (int)(tex.width * hit.textureCoord.x); //row
int column = (int)(tex.height * hit.textureCoord.y);//col
 
//calc pixel in via text coords
int pixIn = (column * tex.width) - (tex.width - row);
//now alpha this pixel and an area around it
}
In the code above, pixIn and an area around it will be alphaed exposing the map below the fog.
From there it us up to you how to alpha the texture. I’m currently doing this procedurally with a buffer. I hope this helps someone getting started on a system like this. I’ll post some pics below of my first iteration. Please post any questions in the comments.



Wednesday, September 12, 2012

C to Unity Callback

This is an old post migrated from my previous blog (09/01/2012). I apologize if any info seems outdated.

This post will be sort of specific to those of you who may be writing/integrating an unmanaged API into Unity.
You might find yourself in a situation where some event or request may take place in your API and you need to notify Unity of this. One option is polling and that might be fine…but sometimes that can be sloppy, somewhat inefficient, or maybe just a poor way of solving your problem. Another option using callback.
In my simple example, the API is going to receive a network message then via function pointers we will call a function in Unity passing in the message . I’m actually going to be yanking some of this code directly out of my GummyNet API.
The first thing you want to do is define the type of function used for the callback. Notice that I’m passing the info, a string, as a parameter.
typedef void (__stdcall *OnGummyMessage_Callback)(char*);
You then need to set up a handler. We will be assigning our Unity function to this.
static OnGummyMessage_Callback OnGummyMessage;
You will also need a C function that Unity calls to assign the function pointer. It might look something like this:
EXPORT_API void SetCallback_OnGummyMessage(OnGummyMessage_Callback funcPtr)
{
 OnGummyMessage = funcPtr;
}
Now the Unity Side. Our objective here is to write the import for our set function. Declare delegate object (basically a  function pointer) that defines our method type instantiate it, and pass it to via our set function.
//Declaring the delegate
public delegate void OnGummyMessage_Callback(string msg);
 
//Instantiate the delegate and pass it
void RegisterCallbacks()
{
 OnGummyMessage_Callback onMsgCB = new OnGummyMessage_Callback(this.OnGummyMessage);
 SetCallback_OnGummyMessage(onMsgCB);
}
 
public void OnGummyMessage(string msg)
{
 print("receveied msg: " +msg);
}
 
//Importing the set function
[DllImport ("gummy_server")]
private static extern void SetCallback_OnGummyMessage(OnGummyMessage_Callback funcPtr);
Now when we Invoke our handler (shown below) in the API the C# OnGummyMessage should get called :)
...
//pass the message
OnGummyMessage((char*)data );
...