I moved to a new URL! Check it out!

posts tagged with: csharp

Dev Log: Using Config Objects

Dev Log: Using Config Objects
One of the recent changes in Otter is the ability to configure the RichText object with a RichTextConfig object. This was inspired by something I saw some friends of mine doing in their project. Instead of having a long drawn out list of possible parameters for the creation of an object, instead you can pass in a config object that has all of those parameters set. Here's a quick example.
//In a static class that holds all the Config objects
public static RichTextConfig RTSkyCellStat = new RichTextConfig() {
ShadowColor = G.Colors.Dark,
OutlineColor = G.Colors.Dark,
OutlineThickness = 3,
CharColor = G.Colors.Light,
ShadowY = 3,
Font = Assets.FontHud,
MonospaceWidth = 16,
FontSize = 28
};

And creating the RichText object with this looks like this:
public RichText TextHealth = new RichText("600", Config.RTSkyCellStat);

One of the coolest things about using a Config object is that one Config object can be used for a bunch of different RichText objects. This means that I can define common styles of RichText in a static class somewhere and reuse them as much as I want, so if I need to change something across all of those RichText objects all I need to do is change the config.

I'm not sure if this is the best method of doing this in C# land but so far it seems to be working pretty well. I'm also using Configs for a lot of my UI elements as it lets me define a couple of different styles for panels and buttons and reuse them for elements that share similar roles.

Dev Log: Enemy Waves

Dev Log: Enemy Waves
Waves of enemies can be a pretty confusing thing to manage. It sounds simple at first, but the amount of ways that you can manage a group of enemies entering the game seems nearly endless. Usually in games where I have waves of enemies I don't have enough time to think of an elegant solution. I just usually end up with some sort of random enemy generator and over time I add more potential enemy types to the pool. This works most of the time but can often lead to really weird patterns, or nearly impossible to survive scenarios if its not tuned correctly.

For this game I have a little bit more time than a weekend to complete it, so this gives me an opportunity to try and come up with a cool solution. For the current design of the game there exist enemy spawner tiles in the game world. These tiles are present from the very start of the session, although all of them might not be active yet.

Enemies can spawn from any one of the active tiles in the scene. There is always at least one active enemy spawner from the start. An enemy wave consists of a list of enemies, and each one of those list entries also knows what enemy spawner they should come from, and how long they should wait before appearing.

When I have a wave ready to go I can add it into my EncounterManager object which will then execute each wave. An enemy wave can either wait for a certain amount of time before spawning the next one, or it can wait for all of the enemies to be cleared before spawning the next one.

So with all of that, this is what it currently looks like to set up enemy waves:
var wave2 = new EnemyWaveProperties()
.Add(typeof(EnemyBitty))
.SpawnFrom(1)
.Add(typeof(EnemyBitty))
.SpawnFrom(0)
.Delay(120)
.Add(typeof(EnemyPopcorn))
.SpawnFrom(1)
.Add(typeof(EnemyPopcorn))
.Delay(120)
.SpawnFrom(0)
.Add(typeof(EnemyBitty))
.Add(typeof(EnemyBitty))
.Add(typeof(EnemyBitty));

EncounterManager.AddAction(new EncounterActionEnemyWave(wave2));
And here's a quick look at what it looks like when the encounter manager is executing an enemy wave action.
public override void Execute() {
foreach(var wave in properties.Waves) {
var spawner = EnemySpawner.GetSpawnerById(wave.SpawnerId);

foreach (var waveEnemy in wave.Enemies) {
if (Spawning) {
if (Timer == waveEnemy.SpawnDelay) {
var enemy = spawner.Spawn(waveEnemy.EnemyType);
EnemiesSpawned.Add(enemy);
SpawnedFirstEnemy = true;
}
}
}
}

if (Timer >= properties.MaxSpawnDelay) {
Spawning = false;
}

if (WaitForClear && SpawnedFirstEnemy) {
var enemiesDead = true;
foreach (var enemy in EnemiesSpawned) {
if (enemy.IsInScene) { // Enemy is still alive
enemiesDead = false;
}
}
if (enemiesDead) {
Finished = true;
EnemiesSpawned.Clear();
}
}
else {
if (Timer >= Time) {
Finished = true;
}
}

Timer++;
}
Nothing too crazy, I think!

Dev Log: Impact Effects

Dev Log: Impact Effects
Whoops, been kinda neglecting my poor blog for a week. I've been making some progress on my fancy game project though! Just have been forgetting to post about it.

Image


One of the things I tackled over the last couple of days was adding more visual effects for stuff like damage impacts. I want damage to feel over the top juicy at all times so that every impact is really felt by the player. The effect I ended up with for damage impacts is an inverted flash combined with some red colored mixing and additive blending.

Image


Right now I'm using one utility shader that has a bunch of parameters on it for various effects. Check it out:
#version 120
uniform sampler2D texture;
uniform sampler2D noiseTexture;
uniform vec4 overlayColor;
uniform vec4 additiveColor;
uniform vec4 subtractiveColor;
uniform float overlayNoise;
uniform float inverted;
uniform float noiseX;
uniform float noiseY;

void main() {
//get color of this pixel
vec2 pixpos = gl_TexCoord[0].xy;
vec4 pixcol = texture2D(texture, pixpos);

vec4 outcol = abs(inverted-pixcol);
outcol.a = pixcol.a;

//mix in the overlay color
outcol = mix(outcol, overlayColor, overlayColor.a);

//add the additive color
outcol += additiveColor * additiveColor.a;

//subtract the subtractive color (DUH)
outcol -= subtractiveColor;

vec4 noiseColor = texture2D(noiseTexture, mod(pixpos, 1) + vec2(noiseX, noiseY));
outcol = mix(outcol, noiseColor, overlayNoise);

//reset alpha to prevent coloring transparent pixels
outcol.a = pixcol.a;

//output the final color
gl_FragColor = outcol;
}
I'm still learning the ins and outs of shaders so this probably isn't the best way to do this, but for now it seems to be working out fine.

Along with this shader there is some code in my "Combatant" component to control the shader. The Combatant has a timer that is set whenever it takes damage. This timer is then used to control various parameters on the shader. Every 2 frames the image is inverted using the shader. When the image is inverted there's a red additive color blend applied to the image, and when the image is not inverted there is a normal red color mix applied. The intensity of the color mix is determined by the timer. It starts very intense then fades away.

On top of that another texture is blended with the image. The other texture is just a simple image of generated noise. I'm not totally sure why, but for some reason I like the noise texture along with the rest of the effects. It kind of represents a disruption to the target taking damage, or something poetic like that.

Last but not least the image also shakes around a bit. This is something I first noticed a lot while playing Street Fighter 4. An action freeze along with sprite shaking is an incredibly useful way to convey an intense impact.

Here's the little blurb of code that handles the effects for Combatants
//Handle graphics
foreach (var img in Images) {
var overlay = Util.ScaleClamp(StunEffect, 0, StunEffectMax, 0, 0.5f);
var color = new Color(Color.Black) { A = overlay };
var addColor = new Color(StunColor) { A = overlay };

img.Shader.SetParameter("overlayNoise", overlay * 0.5f);
img.Shader.SetParameter("noiseX", Rand.Float(0, 0.25f));
img.Shader.SetParameter("noiseY", Rand.Float(0, 0.25f));

if (StunEffect > StunEffectMax * 0.25f) {
addColor.A = 0.5f;
color = G.Colors.Dark;
color.A = 0.25f;
img.Shader.SetParameter("inverted", StunEffect % 4 > 1 ? 1 : 0);
}
else {
img.Shader.SetParameter("inverted", 0);
}

img.Shader.SetParameter("overlayColor", color);
img.Shader.SetParameter("additiveColor", addColor);

img.Shake = Util.ScaleClamp(StunEffect, 0, StunEffectMax, 0, 30);
}
Along with the impact effects the Bullet entities have an impact effect to help show damage. If bullets hit something and deal damage they spawn a small red and yellow explosion, and if they don't do damage then the particle is blue and cyan. This is something I saw when I played a lot of Thunder Force III as a kid!

Dev Log: Quick Lighting Test

Dev Log: Quick Lighting Test
As a quick experiment I wanted to see how Otter would be equipped to handle a simple lighting set up. The basic set up is just a big render texture that is filled with a dark color with a blend mode set to multiply. Then light is rendered to the render texture with a blend mode of additive. The result is a layer of shadow that can have light rendered to it.

Image


The code for this set up right now is pretty straight forward as well. I'm using a black and white image for the light. Just a black rectangle with a white radial gradient in the center.

Here's some sample code to show how this effect is achieved with Otter!
//set up the surface
public Surface SurfaceLighting = new Surface(Game.Instance.Width, Game.Instance.Height, new Color("379")) {
Blend = BlendMode.Multiply
};

//set up the light
public Image ImageLight = new Image(Assets.ImageLight1) {
Blend = BlendMode.Add
};

//add the surface to an entity to render it
//this happens in an object's initialization
AddGraphicGUI(SurfaceLighting);

//render light to the surface
//this happens in a Render() function
Draw.SetTarget(SurfaceLighting);
ImageLight.Color = Color.White;
Draw.Graphic(ImageLight, Input.MouseX, Input.MouseY);
ImageLight.Color = Color.Red;
Draw.Graphic(ImageLight, Input.MouseX + 500, Input.MouseY);
ImageLight.Color = Color.Blue;
Draw.Graphic(ImageLight, Input.MouseX - 500, Input.MouseY);
Draw.ResetTarget();

Dev Log: Anti-clumping Made Easy

Image


Starting to get back into a bit of a groove on this game thing. One little fun thing to work on was the enemy anti-clumping code. I don't want any enemies to stack on top of each other (although it would be smart of them to do so in order to conceal their numbers.) With a short bit of code I can have enemies push each other away, similar to how babies and rocks push away from each other in Offspring Fling.
public virtual void PushAway() {
if (Hitbox != null) {
if (Overlap(X, Y, (int)Tags.Enemy)) {
var e = Overlapped as Enemy;
if (e.Mass >= Mass) {
var push = new Vector2(X - Overlapped.X, Y - Overlapped.Y);

if (push.X == 0 && push.Y == 0) {
push = new Vector2(Rand.Float(-1, 1), Rand.Float(-1, 1));
}

push.Normalize(pushAwayForce);
pushAwaySpeed += push;
}
}
}

var length = Util.Approach((float)pushAwaySpeed.Length, 0, pushAwayForce * 0.5f);

pushAwaySpeed.Normalize(length);


X += (float)pushAwaySpeed.X * 0.01f;
Y += (float)pushAwaySpeed.Y * 0.01f;
}
Pretty neat! This is actually pretty similar to the original code in the prototype many many years ago, except now it's in fancy C# instead of GML. Enemies will call PushAway() every update.

Dev Log: Coroutine Example

Image


Thanks to knowledge passed down from Chevy Ray I was able to get Coroutines working in Otter recently! Coroutines are magical chunks of code that are able to yield their execution and remember their state. It's bonkers what you can do with them using this power.

I added an example to Otter to hopefully help out any folks that are looking into using them:
using Otter;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoroutineExample {
class CoroutineScene : Scene {

public Image ImageBox = Image.CreateRectangle(50);

public Color NextColor = Color.White;
public Color CurrentColor = Color.White;

public CoroutineScene() : base() {
// Center that box.
ImageBox.CenterOrigin();

// Gotta draw the box.
AddGraphic(ImageBox);

// Set the box position.
ImageBox.X = 100;
ImageBox.Y = 100;
}

public override void Begin() {
base.Begin();

// Start the coroutine, yo.
Game.Coroutine.Start(MainRoutine());
}

/// <summary>
/// The main coroutine to execute. This will move the box around and change its color.
/// </summary>
/// <returns>Whatever a coroutine thing returns. Sometimes 0 I guess.</returns>
IEnumerator MainRoutine() {
// Wait for 30 frames.
yield return Coroutine.Instance.WaitForFrames(30);
// Set the next color.
NextColor = Color.Red;
// Move the box to the top right.
yield return MoveBoxTo(540, 100);

// Wait for 30 frames.
yield return Coroutine.Instance.WaitForFrames(30);
// Set the next color.
NextColor = Color.Yellow;
// Move the box to the bottom right.
yield return MoveBoxTo(540, 380);

// Wait for 30 frames.
yield return Coroutine.Instance.WaitForFrames(30);
// Set the next color.
NextColor = Color.Green;
// Move the box to the bottom left.
yield return MoveBoxTo(100, 380);

// Wait for 30 frames.
yield return Coroutine.Instance.WaitForFrames(30);
// Set the next color.
NextColor = Color.Cyan;
// Move the box to the top left.
yield return MoveBoxTo(100, 100);

// Start a new coroutine.
Game.Coroutine.Start(MainRoutine());
}

IEnumerator MoveBoxTo(float x, float y) {
// Used to determine the completion.
var initialDistance = Util.Distance(ImageBox.X, ImageBox.Y, x, y);

float currentDistance = float.MaxValue;
while (currentDistance > 1) {
currentDistance = Util.Distance(ImageBox.X, ImageBox.Y, x, y);

// Determine the completion of the movement from 0 to 1.
var completion = Util.ScaleClamp(currentDistance, 0, initialDistance, 1, 0);

// Lerp the color of the box.
ImageBox.Color = Util.LerpColor(CurrentColor, NextColor, completion);

// Spin the box along with its movement.
ImageBox.Angle = Util.ScaleClamp(completion, 0, 1, 0, 360);

// Actually move the box.
ImageBox.X = Util.Approach(ImageBox.X, x, 5);
ImageBox.Y = Util.Approach(ImageBox.Y, y, 5);

// Wait until next frame.
yield return 0;
}

// Done moving. Update the color.
CurrentColor = NextColor;
}
}
}
I'm actually totally not sure if I'm doing it correctly in the example, but it seems to be working out well so far. Going to try using them for various things now in my current projects!