Code - R3

Nature of Code 之 3 - Oscillator .

#ifndef __OSCILLATOR_H__
#define __OSCILLATOR_H__

#include "rnd.h"
#include "v2d.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct Oscillator {
  Vec2D angle;
  Vec2D Posi;
  Vec2D velocity;
  Vec2D amplitude;
  float mass;
  float dir;
  void (*Update)(struct Oscillator *self);
  void (*Destroy)(struct Oscillator *self);
} Oscillator;

Oscillator *NewOscillator(void);

static void _update(Oscillator *osc) {
  Vec2D lastPosi = V2D_Clone(osc->Posi);
  osc->angle = V2D_Add(osc->angle, osc->velocity);
  osc->Posi.x = sin(osc->angle.x) * osc->amplitude.x;
  osc->Posi.y = sin(osc->angle.y) * osc->amplitude.y;
  osc->dir = V2D_Angle(lastPosi, osc->Posi);
}
static void _destroy(Oscillator *self) {
  if (self != NULL) {
    free(self);
    self = NULL;
  }
}
Oscillator *NewOscillator(void) {
  Oscillator *osc = (Oscillator *)malloc(sizeof(Oscillator));
  if (osc != NULL) {
    osc->angle = V2D_Zero();
    osc->velocity = V2D_Set(rnd_Fn(0.1) - 0.05, rnd_Fn(0.1) - 0.05);
    osc->amplitude = V2D_Set(rnd_R32n(0, 400), rnd_R32n(0, 300));
    osc->Posi = V2D_Clone(osc->amplitude);
    osc->dir = 0;
    osc->Update = &_update;
    osc->Destroy = &_destroy;
  }
  return osc;
}

#endif // header guard

完整的在這裏

c  program  sgi 

See also