]> git.itanic.dy.fi Git - sdl-planets/commitdiff
planets: Add function to merge two planets at one
authorTimo Kokkonen <kaapeli@itanic.dy.fi>
Sun, 7 Mar 2010 11:56:29 +0000 (13:56 +0200)
committerTimo Kokkonen <kaapeli@itanic.dy.fi>
Sun, 7 Mar 2010 11:56:29 +0000 (13:56 +0200)
This is used when two planets collide and other planet is merged in
the another one.

Signed-off-by: Timo Kokkonen <kaapeli@itanic.dy.fi>
planet.c
planet.h

index 47d82f3adedae0d2ac388d12a6963fcd351931e9..73bde0fedcfd08756edd097bffec556458287c1e 100644 (file)
--- a/planet.c
+++ b/planet.c
@@ -80,6 +80,43 @@ int gravitize_planets(struct planet *a, struct planet *b, const double time)
        return 0;
 }
 
+/*
+ * Merge planets a and b into planet a
+ *
+ * It is left for the caller to deal with the scrap planet b
+ */
+static void _merge_planets(struct planet *a, struct planet *b)
+{
+       struct vector pa, pb, p;
+
+       vector_scale(&a->speed, a->mass, &pa);
+       vector_scale(&b->speed, b->mass, &pb);
+       vector_add(&pa, &pb, &p);
+
+       vector_scale(&a->pos, a->mass, &a->pos);
+       vector_scale(&b->pos, b->mass, &b->pos);
+
+       a->mass += b->mass;
+       vector_div(&a->pos, a->mass, &a->pos);
+       reshape_planet(a);
+       vector_div(&p, a->mass, &a->speed);
+}
+
+/*
+ * Merge planets a and b into a the new planet a, which pointer is
+ * returned to the caller. Planet b is removed from the linked list
+ * and it's memory is freed. The merged planet will retain in the
+ * list.
+ */
+struct planet *merge_planets(struct planet *a, struct planet *b)
+{
+       _merge_planets(a, b);
+
+       list_del(&b->list);
+       free(b);
+       return a;
+}
+
 void move_planet(struct planet *p, const double time)
 {
        struct vector tmp;
index 78cf937ef6626bd4aaa1baa2447dcf48643efbd5..b57c108a069d43038792d1d5cffd4589b23fb42f 100644 (file)
--- a/planet.h
+++ b/planet.h
@@ -21,6 +21,7 @@ struct planet {
 void init_planet(const SDL_Surface *screen, struct planet *p);
 void draw_planet(SDL_Surface *screen, struct planet *p);
 int gravitize_planets(struct planet *a, struct planet *b, const double time);
+struct planet *merge_planets(struct planet *a, struct planet *b);
 void move_planet(struct planet *p, const double time);
 void print_planet(const struct planet *p);