Begin your C# Game Development Journey Using This Challenge

Begin your C# Game Development Journey Using This Challenge

Hi Fellows,

Here we will discuss a simple but important programming challenge that will help you enhance your fundamental knowledge of C# .NET Console Applications, Data Types, Declaring Variables, Constants, & mathematical operations that are critical for game development.

C# Pre-requisites

  1. Declaring and using variables
  2. Calculating with integers, floats and doubles.
  3. Prompting for inputs and Getting inputs
  4. Declaring and Using Constants and Variables
  5. Trigonometry with floats
  6. Calculations and Rounding

Challenge Description

Here you want to have an impossible imagination. What if you are about to visit ancient Greek and meet Pythagoras, Hipparchus using a time machine. And you visit them with modern computers and games you developed using their amazing mathematical theories like Trigonometry and Pythagoras Theorem.

So on that occasion, you are about to show a simple program to show them how you implemented the Pythagoras theorem using C# Programming Language.

Wait !! Pythagoras' theorem is a critical theorem used in game development mostly to calculate the distance between two points.

The Pythagoras Theorem

The Pythagorean Theorem tells us how to calculate the length of the hypotenuse of a right triangle.

Image description

Then,

Image description

Here are some applications of the theorem.

Image description

**

Challenge !!

**

In the following scenario, Imagine there are two players. Player A wants to throw a projectile at Player B as they are enemies.

The requirement for Projectile Throwing is the Direction and distance of Player B from Player A's position.

Image description

First of all, we have to take the current positions of 2 Players as x y coordinates imagining a 2D cartesian plane.

Player A -> (point1X, point1y) Player B-> (point2X, point2y)

So Let's Implement it in C# Script.

using System;
using System.Runtime.ConstrainedExecution;

namespace GameDevPythagoras
{
    /// <summary>
    /// Pythagoras Implementation for position calculation using C#
    /// </summary>
    class Program
    {
        // declaring x and y coordinates for player positions
        static float point1X;
        static float point1Y;
        static float point2X;
        static float point2Y;

then we can assign values for declared variables using the C# input function. Here we input data as a one-line string.

Player A's XY Coordinates and Player B's XY Coordinates Separated by spaces like below,

5 5 4 4

Also we assign q to end the while loop.

/// <param name="args">command-line args</param>
static void Main(string[] args)
{
    // loop while there's more input
    string input = Console.ReadLine();
    while (input[0] != 'q')

Then we read the input and assign values for points using the following function.

static void GetInputValuesFromString(string input)
{
    // extract point 1 x
    int spaceIndex = input.IndexOf(' ');
    point1X = float.Parse(input.Substring(0, spaceIndex));

    // move along string and extract point 1 y
    input = input.Substring(spaceIndex + 1);
    spaceIndex = input.IndexOf(' ');
    point1Y = float.Parse(input.Substring(0, spaceIndex));

    // move along string and extract point 2 x
    input = input.Substring(spaceIndex + 1);
    spaceIndex = input.IndexOf(' ');
    point2X = float.Parse(input.Substring(0, spaceIndex));

    // point 2 y is the rest of the string
    input = input.Substring(spaceIndex + 1);
    point2Y = float.Parse(input);
}

Then inside the previous while loop, we call the above function to assign values from the input.

// extract point coordinates from string
GetInputValuesFromString(input);

Next, we are going to calculate the distance between 2 points as a float. To do the implementation of the Pythagoras Theorem, we want the delta x and delta y as 2 vertices of the triangle.

Image description

To do the next calculations, we are going to use the Math class in C#.

Calculating Distance

  1. Math.Sqrt -> Returns the square root of a specified number as a Double.
  2. Math.Pow -> Returns a specified number raised to the specified power as a Double.
  3. Math.Atan2 -> Returns the angle whose tangent is the quotient of two specified numbers as a Double.

So we calculate the distance between 2 player positions as follows.

float distance = (float) Math.Sqrt((Math.Pow(point1X - point2X, 2) + Math.Pow(point1Y - point2Y, 2)));

Basically what happens here is,

DeltaX = Player B's X Coordinate Magnitude-Player A's X Coordinate Magnitude DeltaY = Player B's Y Coordinate Magnitude-Player A's Y Coordinate Magnitude

Then, Image description

We use Math.Pow method by giving 2 numbers as the parameters like below,

_

Math.Pow (double x, double y); double x = A double-precision floating-point number to be raised to a power. double y = A double-precision floating-point number that specifies a power. _

We use Math.Sqrt method by giving the number required to calculate the square root as the parameter.

Then we convert calculated double values to float using (float).

Calculating the angle

To calculate the angle we have to use Math.Atan2 method which returns the angle whose tangent is the quotient of two specified numbers.

double angle = (float)Math.Atan2(point2Y - point1Y, point2X - point1X);

This returns the radiant value of the angle, so we need to convert it to degrees to proceed.

angle *= (float)180/Math.PI;   //angle = angle * (float)180/Math.PI

> The Math.PI property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159: Math.PI = π ≈ 3.14159

Next, we print out the calculation answers using Console.WriteLine method in DOT NET.

Console.WriteLine("The Distance Between Player A and B is " + (float) Math.Round(distance, 6));
Console.WriteLine("The Angle from Player A to Player B is " + (float)Math.Round(angle, 5) + " degrees");
input = Console.ReadLine();

Here is a test case.

Image description

Image description

Here you can have look at the source code.

using System;
using System.Runtime.ConstrainedExecution;

namespace GameDevPythagoras
{
    /// <summary>
    /// Pythagoras Implementation for position calculation using C#
    /// </summary>
    class Program
    {
        // declaring x and y coordinates for player positions
        static float point1X;
        static float point1Y;
        static float point2X;
        static float point2Y;


        /// <param name="args">command-line args</param>
        static void Main(string[] args)
        {
            // loop while there's more input
            string input = Console.ReadLine();
            while (input[0] != 'q')
            {
                // extract point coordinates from string
                GetInputValuesFromString(input);

                // calculate distance between points 1 and 2
                float distance = (float) Math.Sqrt((Math.Pow(point1X - point2X, 2) + Math.Pow(point1Y - point2Y, 2)));

                double angle = (float)Math.Atan2(point2Y - point1Y, point2X - point1X);

                angle *= (float)180/Math.PI;

                Console.WriteLine("The Distance Between Player A and B is " + (float) Math.Round(distance, 6));
                Console.WriteLine("The Angle from Player A to Player B is " + (float)Math.Round(angle, 5) + " degrees");
                input = Console.ReadLine();


            }
        }

        /// <summary>
        /// Extracts point coordinates from the given input string
        /// </summary>
        /// <param name="input">input string</param>
        static void GetInputValuesFromString(string input)
        {
            // extract point 1 x
            int spaceIndex = input.IndexOf(' ');
            point1X = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 1 y
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point1Y = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 2 x
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point2X = float.Parse(input.Substring(0, spaceIndex));

            // point 2 y is the rest of the string
            input = input.Substring(spaceIndex + 1);
            point2Y = float.Parse(input);
        }
    }
}

So, I believe this guide would've provided some basic introduction to C# Programming for Game Development as a beginner.

Thank you.