Program to find the steps in order to attack enemies
Game development requires a lot of mathematics, physics, and algorithms, so to practice with CPP in a fun way it can be helpful that you solve problems related to the game. I really enjoy game programming that's why I'm writing this post.
The program that we're going to write is not so hard, it's simple, easy and better for you if you're a beginner programmer in CPP.
Read my another post
Two Dimensional Vector structure
You better know that to represent the position of any object or point in the 2D coordinate-system we use vectors that start from (0,0) and end at position P(x,y). So first, we have to implement a 2d Vector before we can use it in our program.
To implement a Vector we can use either CPP's struct or class, both are same but they are different by default properties that are a struct contains public member by default and a class contains private members.
I'm using the struct to implement a vector structure named as Vector2D
(see the code snippet below).
Code snippet
struct Vector2D
{
float x, y; // 1
Vector2D() = default; // 2
Vector2D(float a, float b) // 3
{
x = a;
y = b;
}
/****************
* Vector Operations *
*****************/
Vector2D& operator += (const Vector2D& velocity)
{
x += velocity.x;
y += velocity.y;
return *this;
}
Vector2D& operator -= (const Vector2D& velocity)
{
x -= velocity.x;
y -= velocity.y;
return *this;
}
Vector2D operator + (const Vector2D& velocity) const
{
return Vector2D(x+velocity.x, y+velocity.y);
}
Vector2D operator - (const Vector2D& velocity) const
{
return Vector2D( x - velocity.x, y - velocity.y );
}
};
-
Inside the Vector2D float x,y represents x and y coordinate,
-
Vector2D() is marked as a default constructor.
-
and there is another constructor which accepts a, strong values, assign them to x,y.
-
This is enough to represent a 2d vector.
-
but we want to do some operations on them such as addition, subtraction, and multiplication of two vectors. To do so I implement some operator overload functions.
Yeah, we've done this! Now we can easily use Vector objects in the program.

Q.How to reach to the enemy?
To better understand what we're going to do See the above image, Player P and enemy E is at 4, 4, and 13, 6 respectively, and in order to attack the Enemy Player P should go some steps to right and up. It is simple to calculate these steps, we have to just subtract vector P(4, 4) from E(13, 6) then we get vector d(9, 2) means that Player p should go 9 steps to the right and 2 steps to up to attack the enemy.
Ans
#include <iostream>
int main() {
float x, y;
std::cout << " Position of the Player--> " << std::endl;
std::cin >> x;
std::cin >> y;
Vector2D p(x, y);
std::cout << " Position of the Enemy--> " << std::endl;
std::cin >> x;
std::cin >> y;
Vector2D e(x, y);
e -= p;
std::cout << "Player
should move " << e.x << "
times right and "
<<
e.y << " times
up to attack " << std::endl;
system("pause");
return 0;
}
No comments:
Post a Comment