"Objektklasse":
Attribute:
Masse
Form
Material
Koordinaten
Bewegungsvektor
Letzte Kollision
Fest auf der Stelle, ja oder nein?
Loop die die Physik jeden Tick macht: (hauptfunktion)
Alle Objekte um ihren Bewegungsvektor bewegen.
Bewegungsvektoren nach Gravität passend verändern (Grabititätsvektor addieren, bzw generieren falls Anziehung von einem Punkt kommt.
Checken ob zwei Objekte kollidieren
->Kollidierungsfunktion aufrufen
Ggf. Reibung abziehen.
Kollisionsfunktion
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Absolut! Gerne setze ich dieses Konzept einer 2D-Physik-Engine in C++ um.
Ich werde den Code so strukturieren, dass er die von Ihnen beschriebenen Konzepte klar widerspiegelt. Für die Vektormathematik, die entscheidend ist, erstelle ich eine einfache Vec2d-Struktur. Das Ergebnis ist ein voll funktionsfähiges, aber minimalistisches Konsolenprogramm, das die Grundlagen demonstriert.
Erklärung der Umsetzung
Vec2d: Eine einfache Struktur für 2D-Vektoren (wie Koordinaten, Geschwindigkeit, Schwerkraft). Sie enthält x- und y-Werte sowie überladene Operatoren (+, -, *, /), um die physikalischen Berechnungen sauber und lesbar zu halten.
Shape und Material: Shape wird ein enum, um zwischen Formen zu unterscheiden (hier nur CIRCLE zur Vereinfachung). Material ist eine struct, die physikalische Eigenschaften wie restitution (Elastizität/Bounciness) und reibung bündelt.
PhysicsObject (Objektklasse): Dies ist die zentrale Klasse. Sie enthält alle von Ihnen genannten Attribute. Die Form-spezifischen Daten (z.B. der Radius für einen Kreis) sind ebenfalls enthalten.
Kollisionsfunktionen:
check_collision: Prüft, ob sich zwei Objekte überschneiden. Die Implementierung hier ist für zwei Kreise (Abstand der Mittelpunkte < Summe der Radien).
resolve_collision: Löst die Kollision auf. Dies ist der physikalisch komplexeste Teil. Er berechnet den Impuls basierend auf Masse und Elastizität und wendet ihn auf die Geschwindigkeitsvektoren beider Objekte an. Er korrigiert auch die Positionen, um ein "Versinken" der Objekte ineinander zu verhindern.
main() (Hauptfunktion/Loop):
Erstellt eine Liste (std::vector) von PhysicsObjects.
Startet eine Schleife, die eine feste Anzahl von "Ticks" simuliert.
In jedem Tick wird die von Ihnen beschriebene Logik ausgeführt: Schwerkraft anwenden, Objekte bewegen, Kollisionen prüfen und auflösen.
(Optional) Eine einfache Randkollision wird hinzugefügt, damit die Objekte nicht aus einem definierten Bereich "fallen".
C++ Code
cpp
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm> // Für std::min
// Eine einfache 2D-Vektor-Klasse für Position, Geschwindigkeit, etc.
struct Vec2d {
double x = 0.0, y = 0.0;
// Operatoren für einfache Vektormathematik
Vec2d operator+(const Vec2d& other) const { return {x + other.x, y + other.y}; }
Vec2d operator-(const Vec2d& other) const { return {x - other.x, y - other.y}; }
Vec2d operator*(double scalar) const { return {x * scalar, y * scalar}; }
Vec2d operator/(double scalar) const { return {x / scalar, y / scalar}; }
void operator+=(const Vec2d& other) { x += other.x; y += other.y; }
void operator-=(const Vec2d& other) { x -= other.x; y -= other.y; }
double magnitude() const { return std::sqrt(x * x + y * y); }
Vec2d normalized() const {
double mag = magnitude();
if (mag > 0) return {x / mag, y / mag};
return {0, 0};
}
double dot(const Vec2d& other) const { return x * other.x + y * other.y; }
};
// --- Definitionen laut Ihrer Vorgabe ---
// Attribut: Form (hier vereinfacht als Enum)
enum class Shape {
CIRCLE
// RECTANGLE, POLYGON, etc. könnten hier hinzugefügt werden
};
// Attribut: Material
struct Material {
double restitution; // Elastizität (0 = unelastisch, 1 = perfekt elastisch)
double friction; // Reibung (0 = keine, 1 = hohe)
};
class PhysicsObject {
public:
// --- Attribute ---
double mass;
Shape shape;
Material material;
Vec2d position; // Koordinaten
Vec2d velocity; // Bewegungsvektor
bool is_static; // Fest auf der Stelle, ja oder nein?
// Form-spezifische Daten
double radius; // Nur für CIRCLE relevant
// Attribut: Letzte Kollision (hier vereinfacht, um Endlos-Kollisionen zu vermeiden)
// In einer echten Engine wäre dies komplexer (z.B. mit Zeitstempel)
PhysicsObject* last_collision_partner = nullptr;
PhysicsObject(double m, Shape s, Material mat, Vec2d pos, Vec2d vel, bool stat, double r)
: mass(m), shape(s), material(mat), position(pos), velocity(vel), is_static(stat), radius(r) {
if (is_static) {
mass = 1.0e100; // "Unendliche" Masse für statische Objekte
}
}
// Funktion, um das Objekt zu bewegen
void update_position(double dt) {
if (!is_static) {
position += velocity * dt;
}
}
};
// --- Kollisionsfunktionen ---
bool check_collision(const PhysicsObject& a, const PhysicsObject& b);
void resolve_collision(PhysicsObject& a, PhysicsObject& b);
// --- Hauptfunktion (Physik-Loop) ---
int main() {
// Simulations-Setup
std::vector<PhysicsObject> objects;
const Vec2d GRAVITY = {0.0, 9.81}; // Gravitätsvektor
const double dt = 0.05; // Zeitschritt (delta time) für jeden Tick
const int simulation_ticks = 200;
// Erstellen der Objekte
Material bouncy_ball = {0.8, 0.2}; // Sehr elastisch
Material heavy_ball = {0.5, 0.4}; // Weniger elastisch
Material ground_material = {0.5, 0.9}; // Statischer Boden
objects.emplace_back(10.0, Shape::CIRCLE, bouncy_ball, Vec2d{20, 10}, Vec2d{10, 0}, false, 5.0);
objects.emplace_back(20.0, Shape::CIRCLE, heavy_ball, Vec2d{60, 12}, Vec2d{-5, 0}, false, 7.0);
// Eine "Boden"-Linie simulieren durch statische Kreise
for (int i = 0; i < 15; ++i) {
objects.emplace_back(1.0, Shape::CIRCLE, ground_material, Vec2d{i * 7.0, 80}, Vec2d{0, 0}, true, 4.0);
}
// Der Physik-Loop
for (int tick = 0; tick < simulation_ticks; ++tick) {
std::cout << "--- Tick " << tick << " ---" << std::endl;
// 1. Alle Objekte um ihren Bewegungsvektor bewegen.
// (Wird am Ende gemacht, nach der Berechnung der neuen Geschwindigkeit)
// 2. Bewegungsvektoren nach Gravität passend verändern
for (auto& obj : objects) {
if (!obj.is_static) {
obj.velocity += GRAVITY * dt;
}
}
// 3. Checken ob zwei Objekte kollidieren
for (size_t i = 0; i < objects.size(); ++i) {
for (size_t j = i + 1; j < objects.size(); ++j) {
PhysicsObject& obj1 = objects[i];
PhysicsObject& obj2 = objects[j];
if (check_collision(obj1, obj2)) {
// -> 4. Kollidierungsfunktion aufrufen
resolve_collision(obj1, obj2);
}
}
}
// 5. Ggf. Reibung abziehen (hier als einfacher Luftwiderstand implementiert)
for (auto& obj : objects) {
if (!obj.is_static) {
// Einfacher Luftwiderstand, proportional zur Geschwindigkeit
obj.velocity = obj.velocity * 0.999;
}
}
// 1. (Fortsetzung) Nun die Positionen mit der neuen Geschwindigkeit aktualisieren
for (auto& obj : objects) {
obj.update_position(dt);
// Simple Rand-Kollision (damit Objekte nicht aus dem Bild fliegen)
if (obj.position.x - obj.radius < 0 || obj.position.x + obj.radius > 100) {
obj.velocity.x *= -0.8; // Energieverlust am Rand
obj.position.x = std::max(obj.radius, std::min(100.0 - obj.radius, obj.position.x));
}
}
// Positionen der ersten beiden Bälle ausgeben
std::cout << "Ball 1: pos(" << objects[0].position.x << ", " << objects[0].position.y << ") "
<< "vel(" << objects[0].velocity.x << ", " << objects[0].velocity.y << ")" << std::endl;
std::cout << "Ball 2: pos(" << objects[1].position.x << ", " << objects[1].position.y << ") "
<< "vel(" << objects[1].velocity.x << ", " << objects[1].velocity.y << ")" << std::endl;
}
return 0;
}
// --- Implementierung der Kollisionslogik ---
bool check_collision(const PhysicsObject& a, const PhysicsObject& b) {
if (a.shape == Shape::CIRCLE && b.shape == Shape::CIRCLE) {
double dist_sq = (a.position.x - b.position.x) * (a.position.x - b.position.x) +
(a.position.y - b.position.y) * (a.position.y - b.position.y);
double radius_sum_sq = (a.radius + b.radius) * (a.radius + b.radius);
return dist_sq <= radius_sum_sq;
}
// Hier kämen Checks für andere Formen (z.B. Kreis-Rechteck)
return false;
}
void resolve_collision(PhysicsObject& a, PhysicsObject& b) {
if (a.is_static && b.is_static) return; // Zwei statische Objekte kollidieren nicht dynamisch
// Kollisionsnormalvektor (zeigt von a nach b)
Vec2d normal = (b.position - a.position).normalized();
// Relativgeschwindigkeit
Vec2d relative_velocity = b.velocity - a.velocity;
// Geschwindigkeit entlang der Normalen
double vel_along_normal = relative_velocity.dot(normal);
// Nicht auflösen, wenn sich die Objekte bereits voneinander entfernen
if (vel_along_normal > 0) return;
// Kombinierte Elastizität
double e = std::min(a.material.restitution, b.material.restitution);
// Impuls-Skalar berechnen (j)
double inv_mass_a = a.is_static ? 0 : 1.0 / a.mass;
double inv_mass_b = b.is_static ? 0 : 1.0 / b.mass;
double j = -(1 + e) * vel_along_normal / (inv_mass_a + inv_mass_b);
// Impulsvektor anwenden
Vec2d impulse = normal * j;
if (!a.is_static) a.velocity -= impulse * inv_mass_a;
if (!b.is_static) b.velocity += impulse * inv_mass_b;
// ---- Reibung (Friction) ----
// Tangentialer Vektor zur Kollision
Vec2d tangent = relative_velocity - normal * vel_along_normal;
if(tangent.magnitude() > 0.001) {
tangent = tangent.normalized();
}
// Impuls in tangentialer Richtung (Reibungsimpuls)
double jt = -relative_velocity.dot(tangent);
jt /= (inv_mass_a + inv_mass_b);
// Kombinierte Reibung
double mu = std::sqrt(a.material.friction * a.material.friction + b.material.friction * b.material.friction);
// Reibungsimpuls darf nicht größer sein als der normale Impuls (Coulombsches Gesetz)
Vec2d friction_impulse;
if(std::abs(jt) < j * mu) {
friction_impulse = tangent * jt;
} else {
friction_impulse = tangent * -j * mu;
}
if (!a.is_static) a.velocity -= friction_impulse * inv_mass_a;
if (!b.is_static) b.velocity += friction_impulse * inv_mass_b;
// ---- Positionskorrektur (um "Versinken" zu beheben) ----
const double percent = 0.4; // Wie stark korrigiert wird (0.2-0.8 ist üblich)
const double slop = 0.01; // Puffer, um Wackeln zu vermeiden
double penetration = (a.radius + b.radius) - (a.position - b.position).magnitude();
Vec2d correction = normal * std::max(penetration - slop, 0.0) / (inv_mass_a + inv_mass_b) * percent;
if (!a.is_static) a.position -= correction * inv_mass_a;
if (!b.is_static) b.position += correction * inv_mass_b;
}