void Tema1::FrameStart()
{
// Set the background color to blue for the sky
glClearColor(0.529f, 0.808f, 0.922f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
// Sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
}
float Tema1::CalculateTankY(float tankX) {
// Căutăm punctele A și B din heightMap care încadrează x-ul tancului
for (size_t i = 0; i < numSquare; ++i) {
float x1 = xPositions[i];
float y1 = heightMap[i];
float x2 = xPositions[i + 1];
float y2 = heightMap[i + 1];
Assistant
if (tankX >= x1 && tankX <= x2) {
// Calculăm t conform formulei
float t = (tankX - x1) / (x2 - x1);
// Calculăm coordonata y a tancului
return y1 + t * (y2 - y1);
}
}
return 0; // În cazul în care tankX este în afara intervalului de puncte (nu ar trebui să se întâmple)
// Start from the tip of the turret
glm::vec2 pozitieVarfTun = tipTurret;
// Generate trajectory points
for (int i = 0; i < numPuncte; ++i) {
float t = i * intervalTimp;
// Calculate the position on trajectory at time t
glm::vec2 pozitie;
pozitie.x = pozitieVarfTun.x + vitezaInitiala * cos(unghiTurret) * t;
pozitie.y = pozitieVarfTun.y + vitezaInitiala * sin(unghiTurret) * t - 0.5f* gravitatie * t * t;
// Add the point to trajectory
puncteTraiectorie.push_back(pozitie);
// Stop if the point goes below the terrain
if (pozitie.y < 0) break;
}
return puncteTraiectorie;
void Tema1::DeformTerrain(glm::vec2 impactPoint, float radius) {
for (size_t i = 0; i < numSquare + 1; ++i) {
float dist = abs(xPositions[i] - impactPoint.x);
if (dist < radius) {
// Calculate normalized distance from impact point
float normalizedDist = dist / radius;
// Use a quadratic function for a smoother, circular distribution
float deformation = (1 - normalizedDist * normalizedDist) * (radius / 2.0f);
// Lower the terrain by the deformation amount, ensuring it does not go below zero
heightMap[i] = max(heightMap[i] - deformation, 0.0f);
}
}
}
void Tema1::Update(float deltaTimeSeconds) {
// Codul existent pentru redarea terenului și a tancului
SimulateLandslide(deltaTimeSeconds);
DrawTerrain();
UpdateTank(tankX, tank1Health, deltaTimeSeconds, "Tank1");
// Desenează proiectilele
// Update and render projectiles
for (auto& proj : proiectile) {
if (!proj.active) continue;
//// Update projectile position
proj.position += proj.velocity * deltaTimeSeconds;
// Apply gravity
proj.velocity.y -= gravitatie * deltaTimeSeconds;
// Deactivate projectile if it goes below the terrain
for (int i = 0; i < numSquare; ++i) {
float x1 = xPositions[i];
float y1 = heightMap[i];
float x2 = xPositions[i + 1];
float y2 = heightMap[i + 1];
glm::vec2 tank1Position(tankX, CalculateTankY(tankX));
glm::vec2 tank2Position(tank2X, CalculateTankY(tank2X));
if (CheckCircleCollision(proj.position, projectileRadius, tank1Position, tankRadius)) {
tank1Health = std::max(0.0f, tank1Health - damagePerHit);
proj.active = false;
}
if (CheckCircleCollision(proj.position, projectileRadius, tank2Position, tankRadius)) {
tank2Health = std::max(0.0f, tank2Health - damagePerHit);
proj.active = false;
}
if (proj.position.x >= x1 && proj.position.x <= x2) {
float t = (proj.position.x - x1) / (x2 - x1);
float hity = y1 * (1-t) + t * y2;
float hitx = x1 * (1 - t) + t * x2;
if (proj.position.y - hity <= 10) {
// Collision detected, deform the terrain
DeformTerrain(proj.position, affectedRadius); // Radius of 50.0f for terrain effect
proj.active = false; // Deactivate projectile
}
}
}
// Render active projectile
if (proj.active) {
modelMatrix = glm::mat3(1);
modelMatrix *= transform2D::Translate(proj.position.x, proj.position.y);
RenderMesh2D(meshes["projectile"], shaders["VertexColor"], modelMatrix);
}
}
void Tema1::UpdateTank(float tankX, float health, float deltaTimeSeconds, const std::string& tankName) {
// Calculează coordonata y și unghiul de înclinare al tancului
if (health <= 0) {
// Tancul este distrus, nu mai desenăm nimic pentru el
return;
}
tankY = CalculateTankY(tankX);
float angle = getAngle(tankX);
void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// Add mouse move event
}
void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button press event
}
void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// Add mouse button release event
}
void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
}
void Tema1::OnWindowResize(int width, int height)
{
}
void Tema1::SimulateLandslide(float deltaTime) {
for (size_t i = 0; i < heightMap.size() - 1; ++i) {
float heightDiff = heightMap[i] - heightMap[i + 1];
if (fabs(heightDiff) > heightDiffThreshold) {
// Calculăm transferul de înălțime bazat pe deltaTime
float heightTransfer = heightTransferRate * deltaTime;
if (heightDiff > 0) {
// Punctul i este mai sus, transferăm o parte din înălțime către punctul i+1
heightMap[i] -= heightTransfer;
heightMap[i + 1] += heightTransfer;
}
else {
// Punctul i+1 este mai sus, transferăm o parte din înălțime către punctul i
heightMap[i] += heightTransfer;
heightMap[i + 1] -= heightTransfer;
}
// Ne asigurăm că nu se transferă mai mult decât este nevoie pentru a ajunge la prag
if (fabs(heightMap[i] - heightMap[i + 1]) < heightDiffThreshold) {
float excess = fabs(heightMap[i] - heightMap[i + 1]) - heightDiffThreshold;
heightMap[i] += (heightDiff > 0 ? excess / 2 : -excess / 2);
heightMap[i + 1] -= (heightDiff > 0 ? excess / 2 : -excess / 2);
}
}
}
}
initializeaza bara de viata din init stiind ca
#include "object2Dtema.h"
Mesh* object2Dtema::CreateCircle(
const std::string& name,
glm::vec3 center,
float radius,
glm::vec3 color,
bool fill,
int numSegments)
{
std::vector vertices;
std::vector indices;
// Dacă desenăm un cerc plin, adăugăm centrul ca prim vertex
if (fill) {
vertices.emplace_back(center, color);
}
float angleStep = 2 * glm::pi<float>() / numSegments;
for (int i = 0; i < numSegments; ++i) {
float angle = i * angleStep;
glm::vec3 position = center + glm::vec3(radius * cos(angle), radius * sin(angle), 0);
vertices.emplace_back(position, color);
if (!fill) {
// Vom folosi GL_LINE_LOOP, deci indicii sunt secvenţiali
indices.push_back(i);
}
else if (i > 0) {
// Adăugăm triunghiuri pentru un cerc plin (GL_TRIANGLE_FAN)
indices.push_back(0); // Centrul cercului
indices.push_back(i); // Punctul curent
indices.push_back(i + 1); // Punctul următor
}
}
// Închide bucla dacă este contur
if (!fill) {
indices.push_back(0);
}
else {
indices.push_back(0); // Închide ultimul triunghi la primul punct de pe circumferință
indices.push_back(1);
}
Mesh* circle = new Mesh(name);
circle->SetDrawMode(fill ? GL_TRIANGLE_FAN : GL_LINE_LOOP);
circle->InitFromData(vertices, indices);
return circle;
ai functiile astea la dispozitie.
bata trebuie sa fie asa:
Bara de viață
Ambele tancuri vor avea deasupra o bară de viață, reprezentată printr-un dreptunghi wireframe (neumplut), peste care va fi suprapus un alt dreptunghi umplut. Bara de viață va scădea atunci când unul dintre proiectile lovește tancul.
si asta e structura tema1.h
#pragma once
#include "components/simple_scene.h"
namespace m1
{
class Tema1 : public gfxc::SimpleScene
{
public:
Tema1();
~Tema1();
void Init() override;
void InitTank();
float CalculateTankY(float tankX);
float getAngle(float tankX);
std::vector<glm::vec2> CalculTraiectorie(float vitezaInitiala, float unghi, float gravitatie, int numPuncte, float intervalTimp, glm::vec2 tipTurret);
void DrawTerrain();
void DeformTerrain(glm::vec2 impactPoint, float radius);
void CheckCollision(glm::vec2 projectilePosition, float collisionThreshold, glm::vec2 impactPoint, float radius);
void SimulateLandslide(float deltaTime);
//void Tema1::DrawHealthBar(glm::vec2 tankPosition);
bool Tema1::CheckCircleCollision(glm::vec2 center1, float radius1, glm::vec2 center2, float radius2);
void Tema1::UpdateTank(float tankX, float health, float deltaTimeSeconds, const std::string& tankName);
private:
void FrameStart() override;
void Update(float deltaTimeSeconds) override;
void FrameEnd() override;
void OnInputUpdate(float deltaTime, int mods) override;
void OnKeyPress(int key, int mods) override;
void OnKeyRelease(int key, int mods) override;
void OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) override;
void OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) override;
void OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) override;
void OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) override;
void OnWindowResize(int width, int height) override;
protected:
float cx, cy;
glm::mat3 modelMatrix;
glm::mat3 modelMatrix1;
glm::mat3 modelMatrix2;
float translateX, translateY;
float scaleX, scaleY;
float angularStep;
float tankX; // Poziția tancului pe axa X
float tankAngle; // Unghiul de înclinare al tancului
float turretAngle; // Unghiul de rotație al turelei
float moveSpeed; // Viteza de deplasare a tancului
float rotationSpeed; // Viteza de rotație a turelei
float tankWidth, tankHeight;
std::vector<float> heightMap; // Harta de înălțime
std::vector<float> xPositions; // Pozițiile x pentru fiecare punct din teren
// TODO(student): If you need any other class variables, define them here.
float maxX, maxY;
float min;
int var, var2;
int numSquare;
//float tankX;
float tankY;
struct Proiectil {
glm::vec2 position;
glm::vec2 velocity;
bool active;
};
std::vector<Proiectil> proiectile;
float vitezaInitiala = 200.0f; // Exemplu de viteză
float gravitatie = 100.0f;
int numPuncte = 100;
float intervalTimp = 0.1f;
int affectedRadius = 100;
glm::vec2 hitPoint = glm::vec2(0, 0);
float heightDiffThreshold = 10.0f; // Prag pentru diferența de înălțime
float heightTransferRate = 20.0f; // Rata de transfer, unități/secundă
//float maxHealth = 100.0f; // Viața maximă a tancului
//float currentHealth = 100.0f; // Viața curentă
//float healthBarWidth = 100.0f; // Lățimea barei de viață
//float healthBarHeight = 10.0f; // Înălțimea barei de viață
//glm::vec3 healthBarColor = glm::vec3(0.0f, 1.0f, 0.0f); // Verde
//glm::vec3 healthBarOutlineColor = glm::vec3(0.0f, 0.0f, 0.0f); // Negru
float tank1Health = 100.0f;
float tank2Health = 100.0f;
const float maxHealth = 100.0f;
const float damagePerHit = 20.0f;
float tank1X = 200.0f;
float tank2X = 1000.0f;
float tankRadius = 50.0f; // Raza cercului de coliziune pentru tanc
float projectileRadius = 5.0f; // Raza cercului de coliziune pentru proiectil
};
} // namespace m1
To initialize the health bars for the tanks, you need to create the mesh for both the filled and wireframe (outline) rectangles representing the health bar. We can use the existing object2Dtema::CreateSquare method with suitable parameters to create these rectangles. Then, initialize them in the Init() method of your Tema1 class. Here is how you can accomplish this:
Create the health bar meshes:
You will need two meshes - one for the filled rectangle indicating the current health and another for the wireframe outline.
Initialize the health bars in Init():
Add this code in your Init() method of Tema1 class to create and add these meshes to the mesh list.
Here's how you can do it:
void Tema1::Init() {
glm::ivec2 resolution = window->GetResolution();
auto camera = GetSceneCamera();
camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0.01f, 400);
camera->SetPosition(glm::vec3(0, 0, 50));
camera->SetRotation(glm::vec3(0, 0, 0));
camera->Update();
GetCameraInput()->SetActive(false);
glm::vec3 corner = glm::vec3(0, 0, 0);
float squareSide = 1;
// Set ground color to brown
Mesh *square = object2Dtema::CreateSquare("square", corner, squareSide, glm::vec3(0.7098f, 0.7412f, 0.5373f), true);
AddMeshToList(square);
numSquare = 1280; // Set the desired number of squares
int step = resolution.x / numSquare;
for (size_t i = 0; i < numSquare + 1; ++i) {
xPositions.push_back(i * step);
heightMap.push_back(30 * gen_y(i * step) + 300);
}
InitTank();
// Create health bar meshes
glm::vec3 healthColorFilled = glm::vec3(0.0f, 1.0f, 0.0f); // Green
glm::vec3 healthColorOutline = glm::vec3(0.0f, 0.0f, 0.0f); // Black
Mesh *filledBar = object2Dtema::CreateSquare("filledBar", glm::vec3(0, 0, 0), 100, healthColorFilled, true);
AddMeshToList(filledBar);
Mesh *wireframeBar = object2Dtema::CreateSquare("wireframeBar", glm::vec3(0, 0, 0), 100, healthColorOutline, false);
AddMeshToList(wireframeBar);
}
Integrate with the UpdateTank method:
Ensure that the health bars are drawn correctly above the tanks with their current health percentage applied.