Begin your C# Game Development Journey Using This Challenge
Tags: csharp, gamedev, programming, unity3d
Published: 2022-04-04 14:02:44

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys5pue00pzbqbc7tq45k.png)

Then,

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ardwp7kw2zc34lgyl9an.png)
  
Here are some applications of the theorem.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2v2pgo8ofo3vza53kxrf.png)

**

#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7e6yjw97u35v0h0d46kx.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lchq0zucs15b5e8b9ty9.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mf2ehcqzz8mnlk0asw9.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urb4kqiiof8yqdej5j9f.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv7m68ouojwmh4c4pfk8.png)

## Here you can have look at the [source code](https://github.com/nawodyaishan/gamedev-pythagoras).

```
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.