Code Samples

Some projects have their souce code avalible so you to browse through using GitFront, so if you wish to see a particular project then see the respective project page. Below are some code samples from some of my projects that I feel are worth showing.

Attack Territory Method (From Merge Conquest)

Language: C#

The method used to attack a territory in merge conquest. The method is on the Battle Manager script that handles the battle logic for the game.

Sample:

/// <summary>
/// Calls for an attack roll and defence roll, the roll result is then run afterwards....
/// Once done it determines if the battle is over or if it should keep going...
/// </summary>
/// <param name="attDiceToRoll">Int | Attacker dice to roll</param>
public void AttackTerritory(int attDiceToRoll, bool autoRoll = false)
{
    if (!autoRoll)
    {
        // Plays the explosion SFX...
        am.PlayRange(explosions, 0, GetRandom.Float(.35f, .5f), GetRandom.Float(.7f, 1.25f));

        // Takes units from territories based on the roll...
        TakeUnitsFromTerritories(attDiceToRoll, move.defendingTerritory.TerritoryStrength, RollAttackMove(attDiceToRoll));

        // Checks the battle state to see if it is over or not...
        CheckActiveBattleState();
    }
    else
    {
		// Takes units from territories based on the roll...
		TakeUnitsFromTerritories(attDiceToRoll, move.defendingTerritory.TerritoryStrength, RollAttackMove(attDiceToRoll));

		Act.OnBattleAttackRoundStart += AutoRoll;
		Act.OnBattleResolved += EndAutoRoll;
                
        // Checks the battle state to see if it is over or not...
        CheckActiveBattleState();
    }
}

Update Stars Method (From Memory Match)

Language: C#

The method used to update the number of stars that were shown at the end of each level that is being played in a non-challenge mode.

Sample:

/// <summary>
/// Updates the star display in sequence to show how many stars the user got on this level...

/// </summary>

/// <remarks>
/// Called via OnUILoad Action & itself...
/// </remarks>
private void UpdateStars()
{
    if (!canUpdateStar) return;
    
    // Stop this from running if the level (or variant of) is not a standard 3 star level...
    if (levelData.levelType != LevelType.Standard) return;
    
    // do nothing if the user didn't gain any stars on the level...
    if (starsGained <= 0) return;

    // Stops the looping effect after all 3 starts are shown...
    if (lastStarUpdated >= 2) return;

    // stops the loop once the users stars gained have all been shown...
    if (lastStarUpdated + 1 >= starsGained) return;
    
    // Disables the challenge star if it is visible...
    if (challengeStar.enabled)
        challengeStar.enabled = false;
    
    // updates the star value to edit
    lastStarUpdated += 1;

    // changes the star sprite to the filled one...
    if (!stars[lastStarUpdated].enabled)
        stars[lastStarUpdated].enabled = true;
    
    stars[lastStarUpdated].sprite = starSprite;
    
    // tween animation for star gained...
    iTween.ScaleFrom(stars[lastStarUpdated].gameObject, Vector3.zero, .5f);
    
    // Play star Audio Clip (only on 1st star)
    am.Play("Twinkle", 0, .25f);

    // restarts this method in-case others stars need updating....
    StartCoroutine(StarCo());
}

Turret.cs (From C.W.I.S)

Language: C#

The turret base class used by the weapons on the ship in C.W.I.S, this controls the turret rotation towards the mouse & the object pooling for the bullets/missiles in the game.

Sample:

/// ------------------------------------------------------------------------------------------------------
/// <summary>
/// Rotates the turret to the mouse position.
/// </summary>
/// <param name="offset">the offset for the rotation if needed.</param>
/// <returns>Quaternion rotation for the object</returns>
/// ------------------------------------------------------------------------------------------------------
internal Quaternion RotateToMousePos(float offset = 0)
{
	InputSystem.onActionChange += (obj, change) =>
	{
		if (change == InputActionChange.ActionPerformed)
		{
			var inputAction = (InputAction)obj;
			var lastControl = inputAction.activeControl;
			device = lastControl.device;
		}
	};

	if (device != null)
	{
		if (device.displayName.Equals("Mouse"))
		{
			Ray ray = cam.ScreenPointToRay(actions.Weapons.Position.ReadValue<Vector2>());
			Plane plane = new Plane(Vector3.up, Vector3.zero);
			float distance;
			float rotation = 0;

			if (plane.Raycast(ray, out distance))
			{
				Vector3 target = ray.GetPoint(distance);
				Vector3 direction = target - transform.position;
				rotation = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + 180f;
			}

			return Quaternion.Euler(0, rotation, 0);
		}
		else
		{
			return Quaternion.Euler(0, Mathf.Atan2(actions.Weapons.PositionJoystick.ReadValue<Vector2>().x, actions.Weapons.PositionJoystick.ReadValue<Vector2>().y) * Mathf.Rad2Deg, 0);
		}
	}
	else
	{
	return Quaternion.Euler(0, 0, 0);
	}
}

UpdateCardVisuals Method (From Detective Notes)

Language: C#

The method that edits the visuals when a user selects an icon from the “editing” popup. This method uses elements of the CarterGames.Utilities Library instead of Int.Parse and ToString().???

Sample:

if (!StringHelper.Get(1, status).Equals(0))
{
	_icons[0].SetActive(false);
	_icons[1].SetActive(true);
	_icons[1].transform.GetChild(0).GetComponentsInChildren<Image>()[0].color = _scm.elements.colors[As.Int(StringHelper.Get(0, status)) - 1];
	_icons[1].transform.GetChild(0).GetComponentsInChildren<Image>()[1].sprite = _scm.elements.icons[As.Int(StringHelper.Get(0, status)) - 1];
	_icons[1].transform.GetChild(0).GetComponentsInChildren<Image>()[1].enabled = true;
	_icons[1].transform.GetChild(1).GetComponentsInChildren<Image>()[0].color = _scm.elements.colors[As.Int(StringHelper.Get(1, status)) - 1];
	_icons[1].transform.GetChild(1).GetComponentsInChildren<Image>()[1].sprite = _scm.elements.icons[As.Int(StringHelper.Get(1, status)) - 1];
	_icons[1].transform.GetChild(1).GetComponentsInChildren<Image>()[1].enabled = true;
}

TabOneDisplay Method (From Save Manager)

Language: C#

The code the runs the display in the first tab of the Save Data Editor in the Save manager asset. It’s purpose is to help the user name a class with savable values.

Sample:

GUI.backgroundColor = Color.green;
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();

if (GUILayout.Button("+ Add Field", GUILayout.Width(90f)))
{
	if (!isCreatingFile)
	{
		isCreatingFile = true;
		types = new List<dataTypes>();
		shouldArray = new List<bool>();
		shouldList = new List<bool>();
		valueNames = new List<string>();
		classNames = new List<string>();
		types.Add(dataTypes.stringValue);
		shouldArray.Add(false);
		shouldList.Add(false);
		valueNames.Add("");
 		classNames.Add("");
	}
	else
	{
		types.Add(dataTypes.stringValue);
		shouldArray.Add(false);
		shouldList.Add(false);
		valueNames.Add("");
		classNames.Add("");
	}
}

GUI.backgroundColor = Color.white;
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();

AI Pathfinding (From AI Maze Solver, 1st Year Uni)

Language: C++

The code that determinded which direction the AI mouse would attempt to travel in and what order it should it should attempt to move based on where it was compared to the exit of the maze.

Sample:

// Calculating the directions 1,2,3,4 for the mouse and setting them to compass directions for movement

// If the piority is to go on the Y axis
if (isY == true)
{
	PosTest = mouse.isPositive(Result.y); // Testing to see whether the mouse shoudld favour up or down

	switch (PosTest)	// Testing the result and setting the compass directions
	{
		case POSITIVE:
		    // If the Y needs to go down
		    DirectionOne = mouse.MoveSouth(); // Sets D1 to South
		    DirectionFour = mouse.MoveNorth(); // Sets D4 to North
		    break;
		case NEGATIVE: 
		    // If the Y needs to go up
		    DirectionOne = mouse.MoveNorth(); // Sets D1 to North
		    DirectionFour = mouse.MoveSouth(); // Sets D4 to South
		    break;
		case NEITHER:
		    // If the exit is on the same Y coord as the mouse (go in default directions)
		    DirectionOne = mouse.MoveSouth(); // Sets D1 to South 
		    DirectionFour = mouse.MoveNorth(); // Sets D4 to North
		    break;
		default:
		    // If there is an error
		    std::cout << "Error (Switch Statement in isY true (D1 & D4))";  // Display error message showing where the error is roughtly
		    break;
	}

	PosTest = mouse.isPositive(Result.x); // Testing to see whether the mouse shoudld favour left or right

	switch (PosTest) // Testing the result and setting the compass directions
	{
		case POSITIVE:
		    // If the X needs to go Right
		    DirectionTwo = mouse.MoveEast(); // Sets D2 to East
		    DirectionThree = mouse.MoveWest(); // Sets D3 to West
		    break;
		case NEGATIVE:
		    // If the X needs to go Left
		    DirectionTwo = mouse.MoveWest(); // Sets D2 to West 
		    DirectionThree = mouse.MoveEast(); // Sets D3 to East 
		    break;
		case NEITHER:
        // If the exit is on the same X coord as the mouse (go in default directions)
		    DirectionTwo = mouse.MoveEast();	// Sets D2 to East
		    DirectionThree = mouse.MoveWest(); // Sets D3 to West
		    break;
		default:
		    // If there is an error
		    std::cout << "Error (Switch Statement in isY true (D2 & D3))"; // Display error message showing where the error is roughtly
		    break;
	}
}

// If the piority is to go on the X axis
if (isY == false)
{
	PosTest = mouse.isPositive(Result.x); // Testing to see whether the mouse shoudld favour left or right

	switch (PosTest) // Testing the result and setting the compass directions
	{
		case POSITIVE:
		    // If the X needs to go Right
		    DirectionOne = mouse.MoveEast(); // Sets D1 to East
		    DirectionFour = mouse.MoveWest(); // Sets D4 to West
		    break;
		case NEGATIVE:
		    // If the X needs to go Left
		    DirectionOne = mouse.MoveWest(); // Sets D1 to West 
		    DirectionFour = mouse.MoveEast(); // Sets D4 to East 
		    break;
		case NEITHER:
		    // If the exit is on the same X coord as the mouse (go in default directions)
		    DirectionOne = mouse.MoveEast(); // Sets D1 to East
		    DirectionFour = mouse.MoveWest(); // Sets D4 to West
		    break;
		default:
		    // If there is an error
		    std::cout << "Error (Switch Statement in isY false (D1 & D4))"; // Display error message showing where the error is roughtly
		    break;
	}

    PosTest = mouse.isPositive(Result.y); // Testing to see whether the mouse shoudld favour up or down

    switch (PosTest) // Testing the result and setting the compass directions
    {
        case POSITIVE:
            // If the Y needs to go down
            DirectionTwo = mouse.MoveSouth(); // Sets D2 to South
            DirectionThree = mouse.MoveNorth(); // Sets D3 to North
            break;
        case NEGATIVE:
            // If the Y needs to go up
            DirectionTwo = mouse.MoveNorth(); // Sets D2 to North
            DirectionThree = mouse.MoveSouth(); // Sets D3 to South
            break;
        case NEITHER:
            // If the exit is on the same Y coord as the mouse (go in default directions)
            DirectionTwo = mouse.MoveSouth(); // Sets D2 to South 
            DirectionThree = mouse.MoveNorth(); // Sets D3 to North
            break;
        default:	
            // If there is an error
            std::cout << "Error (Switch Statement in isY false (D2 & D3))"; // Display error message showing where the error is roughtly
            break;
    }
}