Sign in to follow this  
slayemin

Unity Website for code library?

Recommended Posts

slayemin    6104
I've developed a class called "Range" which keeps track of a number between a min and max number. It's useful for keeping track of any data which could be represented by a progress bar (hitpoints, mana, cooldown time, etc) and generating a random number within the range. I think other people would find it useful within their projects, so I'd like to share it. Is there a section on this site for freely sharing reusable code? In case there isn't, I'm copy/pasting it below. You're free to use it in any way with no strings attached and no guarantee of fitness/correctness.

Note: My code sample is relatively trivial and generic enough to be usable in any game/app. It's 95% tested, but not very rigorously as it should be.

[b]Range.cs - C# XNA Version:[/b]
[CODE]
using System;
using Microsoft.Xna.Framework;
namespace EricsLib
{
/// <summary>
/// The range class gives you a number which is between a min and max number.
/// Usages: -Keeping track of hitpoints or similar metrics
/// -keeping track of ability cool down timers
/// -Generating random numbers within a range
/// -Storing direction angles or other circular data (use looping values)
/// </summary>
public class Range
{
float m_max, m_min; //the thresholds for the meter value
float m_regen; //how many points you want to regenerate/degenerate every second
float m_current; //the current value of the meter
bool m_loopValues; //if this is 'true', then the current value will loop between min and max values instead of being capped.
public Range()
{
m_max = 100;
m_min = 0;
m_current = 100;
m_regen = 0;
m_loopValues = false;
}
/// <summary>
/// Creates a range with the current value at max value and min at zero
/// </summary>
/// <param name="max">the highest range value allowed</param>
public Range(float max)
{
m_max = max;
m_current = max;
m_min = 0.0f;
m_loopValues = false;
}
/// <summary>
/// creates a range value with the current value defaulted to the max value
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
public Range(float min, float max)
{
m_max = max;
m_min = min;
m_current = max;
m_loopValues = false;
}
/// <summary>
/// Creates a range
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current range value</param>
public Range(float min, float max, float current)
{
m_max = max;
m_min = min;
m_current = current;
m_loopValues = false;
}
/// <summary>
/// creates a range value with regeneration/decay value set so the current value increases/decreases over time
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current value in range</param>
/// <param name="regen">the change in current value over time</param>
public Range(float min, float max, float current, float regen)
{
m_max = max;
m_min = min;
m_current = current;
m_regen = regen;
m_loopValues = false;
}
public Range(Range Copy)
{
if (Copy == null)
return;
m_max = Copy.m_max;
m_min = Copy.m_min;
m_current = Copy.m_current;
m_regen = Copy.m_regen;
m_loopValues = Copy.m_loopValues;
}
/// <summary>
/// The current value will always be between min and max values
/// </summary>
public float Current
{
get
{
return m_current; //E: I'm assuming this gets truncated.
}
set
{
//do some quick bounds checking
if (value > m_max) //value is greater than specified max value
{
if (m_loopValues)
{
//the remaining looped value should be seamlessly added to the minimum value if it overflows the max
m_current = m_min + (value % m_max); //tested
}
else
{
m_current = m_max;
}
}
else if (value < m_min) //value is less than specified minimum value
{
if (m_loopValues)
{
m_current = m_min + (value % (m_max - m_min)); //tested
}
else
{
m_current = m_min;
}
}
else
m_current = value;
}
}
/// <summary>
/// Sets the current value to a random number between the min and max range values
/// </summary>
/// <param name="SetCurrent">Flag on whether you want to set the current value to the randomly generated number</param>
/// <returns>the value of current</returns>
public float Random(bool SetCurrent)
{
double d = Calc.random.NextDouble();
float diff = m_max - m_min;
diff *= (float)d;
if (SetCurrent == true)
{
m_current = m_max - diff;
}
return m_max - diff;
}
/// <summary>
/// Returns a random float which lies between min and max value of the range.
/// </summary>
/// <returns></returns>
public float Random()
{
return Random(false);
}
public float Max
{
get
{
return m_max;
}
set
{
m_max = value;
}
}
public float Min
{
get
{
return m_min;
}
set
{
m_min = value;
}
}
public float Half
{
get
{
return (m_min + m_max) / 2.0f;
}
}
/// <summary>
/// Per second regeneration/decay value for the current value of the meter
/// </summary>
public float RegenRate
{
get
{
return m_regen;
}
set
{
m_regen = value;
}
}
public void Update(GameTime gameTime)
{
//are we regenerating/decaying over time?
if (m_regen != 0)
{
Current += m_regen * (gameTime.ElapsedGameTime.Milliseconds);
}
}
public void SetToMax()
{
m_current = m_max;
}
public void SetToMin()
{
m_current = m_min;
}
public bool IsEmpty()
{
return (m_current <= m_min);
}
/// <summary>
/// Set/Get the current value as a percentage of the min and max values
/// </summary>
public float Percent
{
get
{
return ((m_current - m_min) / (m_max - m_min)) * 100;
}
set
{
m_current = m_min + ((value / 100) * (m_max - m_min));
}
}
/// <summary>
/// if this is 'true', then the current value will loop between min and max values instead of being capped.
/// Default: false
/// </summary>
public bool LoopValues
{
get
{
return m_loopValues;
}
set
{
m_loopValues = value;
}
}
/// <summary>
/// Tells you if the current range value is at the maximum value
/// </summary>
/// <returns></returns>
public bool IsMax()
{
return m_current == m_max;
}
/// <summary>
/// Tells you if the current range value is at the minimum value
/// </summary>
/// <returns></returns>
public bool IsMin()
{
return m_current == m_min;
}
}
}
[/CODE]

[b]Range.cs - C# Unity3D version:[/b]
[CODE]
using System;
using UnityEngine;
namespace EricsLib
{
/// <summary>
/// The range class gives you a number which is between a min and max number.
/// Usages: -Keeping track of hitpoints or similar metrics
/// -keeping track of ability cool down timers
/// -Generating random numbers within a range
/// -Storing direction angles or other circular data (use looping values)
/// </summary>
public class Range
{
float m_max, m_min; //the thresholds for the meter value
float m_regen; //how many points you want to regenerate/degenerate every second
float m_current; //the current value of the meter
bool m_loopValues; //if this is 'true', then the current value will loop between min and max values instead of being capped.
public Range()
{
m_max = 100;
m_min = 0;
m_current = 100;
m_regen = 0;
m_loopValues = false;
}
/// <summary>
/// Creates a range with the current value at max value and min at zero
/// </summary>
/// <param name="max">the highest range value allowed</param>
public Range(float max)
{
m_max = max;
m_current = max;
m_min = 0.0f;
m_loopValues = false;
}
/// <summary>
/// creates a range value with the current value defaulted to the max value
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
public Range(float min, float max)
{
m_max = max;
m_min = min;
m_current = max;
m_loopValues = false;
}
/// <summary>
/// Creates a range
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current range value</param>
public Range(float min, float max, float current)
{
m_max = max;
m_min = min;
m_current = current;
m_loopValues = false;
}
/// <summary>
/// creates a range value with regeneration/decay value set so the current value increases/decreases over time
/// </summary>
/// <param name="min">lowest range value</param>
/// <param name="max">highest range value</param>
/// <param name="current">current value in range</param>
/// <param name="regen">the change in current value over time</param>
public Range(float min, float max, float current, float regen)
{
m_max = max;
m_min = min;
m_current = current;
m_regen = regen;
m_loopValues = false;
}
public Range(Range Copy)
{
if (Copy == null)
return;
m_max = Copy.m_max;
m_min = Copy.m_min;
m_current = Copy.m_current;
m_regen = Copy.m_regen;
m_loopValues = Copy.m_loopValues;
}
/// <summary>
/// The current value will always be between min and max values
/// </summary>
public float Current
{
get
{
return m_current; //E: I'm assuming this gets truncated.
}
set
{
//do some quick bounds checking
if (value > m_max) //value is greater than specified max value
{
if (m_loopValues)
{
//the remaining looped value should be seamlessly added to the minimum value if it overflows the max
m_current = m_min + (value % m_max); //tested
}
else
{
m_current = m_max;
}
}
else if (value < m_min) //value is less than specified minimum value
{
if (m_loopValues)
{
m_current = m_min + (value % (m_max - m_min)); //tested
}
else
{
m_current = m_min;
}
}
else
m_current = value;
}
}
/// <summary>
/// Sets the current value to a random number between the min and max range values
/// </summary>
/// <param name="SetCurrent">Flag on whether you want to set the current value to the randomly generated number</param>
/// <returns>the value of current</returns>
public float Random(bool SetCurrent)
{
double d = Calc.random.NextDouble();
float diff = m_max - m_min;
diff *= (float)d;
if (SetCurrent == true)
{
m_current = m_max - diff;
}
return m_max - diff;
}
/// <summary>
/// Returns a random float which lies between min and max value of the range.
/// </summary>
/// <returns></returns>
public float Random()
{
return Random(false);
}
public float Max
{
get
{
return m_max;
}
set
{
m_max = value;
}
}
public float Min
{
get
{
return m_min;
}
set
{
m_min = value;
}
}
public float Half
{
get
{
return (m_min + m_max) / 2.0f;
}
}
/// <summary>
/// Per second regeneration/decay value for the current value of the meter
/// </summary>
public float RegenRate
{
get
{
return m_regen;
}
set
{
m_regen = value;
}
}
public void Update()
{
//are we regenerating/decaying over time?
if (m_regen != 0)
{
Current += m_regen * Time.deltaTime;
}
}
public void SetToMax()
{
m_current = m_max;
}
public void SetToMin()
{
m_current = m_min;
}
public bool IsEmpty()
{
return (m_current <= m_min);
}
/// <summary>
/// Set/Get the current value as a percentage of the min and max values
/// </summary>
public float Percent
{
get
{
return ((m_current - m_min) / (m_max - m_min)) * 100;
}
set
{
m_current = m_min + ((value / 100) * (m_max - m_min));
}
}
/// <summary>
/// if this is 'true', then the current value will loop between min and max values instead of being capped.
/// Default: false
/// </summary>
public bool LoopValues
{
get
{
return m_loopValues;
}
set
{
m_loopValues = value;
}
}
/// <summary>
/// Tells you if the current range value is at the maximum value
/// </summary>
/// <returns></returns>
public bool IsMax()
{
return m_current == m_max;
}
/// <summary>
/// Tells you if the current range value is at the minimum value
/// </summary>
/// <returns></returns>
public bool IsMin()
{
return m_current == m_min;
}
}
}
[/CODE]

Share this post


Link to post
Share on other sites
larsbutler    733
If you want to share code publicly, the proper place to do it is on something like github or bitbucket. And instead of saying "You're free to use it in any way with no strings attached and no guarantee of fitness/correctness", it would be better include a proper source code license file with your code.

Also, if you want your code to be "tested", you should actually write tests for it. If you don't know how, do some research on unit testing and NUnit. You can include the test code with your code above. Otherwise, I not consider this to be "tested" code, now matter how many manual tests you performed.

Hope that helps.

Share this post


Link to post
Share on other sites
[quote name='thok' timestamp='1348610184' post='4983759']
And instead of saying "You're free to use it in any way with no strings attached and no guarantee of fitness/correctness", it would be better include a proper source code license file with your code.[/quote]
Agreed.

[b]@slayemin[/b]: Here's some licenses that you might want:

Suggestion for "[i]free to do whatever[/i]": [url="http://en.wikipedia.org/wiki/MIT_License"]MIT license[/url]
Suggestion for "[i]free to do whatever but give me credit and share changes[/i]": [url="http://www.gnu.org/copyleft/lesser.html"]LGPL[/url]

Suggestion for "[i]I don't care [/i][i]at all[/i][i], just use the code if you want![/i]": [url="http://en.wikipedia.org/wiki/Public_domain"]Public domain[/url] ((this isn't actually a license) [size=2]This only works for countries that have public domain, and you can just ignore the countries that don't - people in those countries will use it anyway and it becomes their problem[/size])

For art, music, photographs, and other non-code works, see [url="http://creativecommons.org/"]Creative Commons[/url]. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Partner Spotlight

  • Similar Content

    • By Levgre
      I have a design doc I can share, either contact me here, at levgree@yahoo.com, or on Discord (tag is levgre#1415). I am only going over some of mechanics in this post, with more focus on combat than campaign, as combat is the core of the game.  designers could possibly be welcome, at the least I don't ever mind getting additional ideas/feedback.
      Like said in the title, the game is inspired by Darkest Dungeon, but aspiring for deeper and more varied combat/campaign mechanics.
      Theme: the player controls a party of raiders that go on missions, getting loot, building up reputation and experience, etc.  These missions would often be populated areas like towns and forts, but also could be caves, forests, and other settings.  
      The player will control a party of 6 characters.  Changing group formation and individual character positions will be an essential part of strategy for all party compositions.   However, most characters will still be in melee combat, as often the party will be fighting off enemies from both sides (just less often from the rear).
      Characters, both friendly and enemy, will be able to die or be severely injured in one hit, and no magical healing available.  However they will be able to dodge or deflect most attacks until they run out of "stamina", at which point they become sluggish and easier to kill.  So gameplay wise, stamina behaves sort of like the regenerating shield in halo.  However if the player makes a tactical error or puts a character in a situation where they are outmatched, characters could still be wounded even at full stamina.  So individual battles are not the only threat, but also tiring  from waves of enemies.
       The player's group can rest when needed, but that will allow the enemies to ready their defenses or get reinforcements.  So speed and smart stamina management is encouraged.  Although, there will be some level of variety in approach, the player could have a more heavily armored team that slogs through tougher fights, or a lightly armored quick characters for a fast team that relies more on the element of surprise. 
      Weapon and armor choices for each character will be significant strategic decisions, based on battle formation and also the strengths and weaknesses of the party comp/individual characters.
      The exact setting is not yet decided, it could be realistic medieval, high fantasy medieval with demihumans and magical creatures and some level of magic, steampunk, etc..  The "raiders" could be seafaring viking types, fighting in a religious conflict like crusaders, or some of both.
      Thanks for reading, and lmk if you are interested or have any questions.
    • By Spronx
      Hi guys,
      I'm Andy from StriX Interactive and we are
      LOOKING FOR A LEVEL DESIGNER
      to join us on this incredible adventure of developing Blood Oath. Open world fantasy 3rd person RPG in the style of The Witcher.
      We plan to launch a Kickstarter campaign by the end of the year. So it's not a paid job yet.
      We need someone capable of making terrain according to the world map that we have and over all level design. We have a great team and want YOU to be a part of it.
      Contact us on our facebook page https://www.facebook.com/StriXInteractive/

    • By Java Nigga
      Hi there!
      We are JN Studios, we are looking for people to work with us in our project.
      About US:
      JN Studios is a 2 people amateur studio. we have like 1 year making games, but this is our first professional project to show it to the public. We are a programmer guy(Me) and a 3d modeller.
      About the game:
      Strategist Sniper is a RPG/FPS game, yes RPG and fps :v you awake in the middle of the unknown and a small voice tells you that you have to go through the world killing other snipers to get out of there. the mechanics of the game are based on the basic controls of games like League of Legends and in FPS games like Counter Strike.
      What we are looking for?
      actually we are looking for another c# programmer, a musician and an artist(for game illustrations for the marketing of the game).
      Profits Share:
      when the game is in a stable alpha phase we will create a campaign in Idiegogo to obtain money to finance the game. each of the project participants will receive a percentage depending on the work done.
      How to apply?
      just send us a email with a portfolio and in what you can help our team -       trabajojava1@gmail.com


      Devblog1.mp4
    • By cursetalegame
      Hello! I am building the main scene in Unity for a 3D cards game. My goal is creating "card slots" to place the different cards from a deck and use it as "buttons". The image below represents somehow what I want to develop. I have been reading and I think that I have to generate a canvas and place in my scene the slots where I want to place the cards, but I am not sure about it. Also, to use the cards, I don't know if setting buttons is the best option (maybe I should use images instead).
      All recommendations and tips are welcome

    • By cursetalegame
      Hi! We are looking for a unity 3D developer to join our small "beginners" team. We are 3 artists (illustration, concept and 3D modeling), 2 designers and 1 programmer (me). We are developing an online video game that we have already designed. Our goal is to create a small studio and build up this game to take it to video game events around Europe and try to find publishers. Also we want to learn step by step how to develop games, so, is better if you don't have a huge experience in developing
      For more information, or any question, you can send us an email to cursetalegame@gmail.com 
      Cheers
  • Popular Now