GSDP:GAM100/CProcessing/vec2 norm()

From Inside
Jump to: navigation, search

vec2_norm()

Description

Returns a copy of the normalized input Vec2. A normalized vector is one where the magnitude (length) is 1. Meaning vec2_length() will always return 1 on a normalized vector.

Parameters

vec2_norm(Vec2 vec)

  • vec - (Vec2) The vector to normalize.

Example

Vec2 position;
Vec2 position2;
Vec2 speed;
Vec2 norm;

void init()
{
  position = vec2_set(canvasWidth / 2, canvasHeight / 4);
  position2 = vec2_set(canvasWidth / 2, 3 * canvasHeight / 4);
  speed = vec2_set(randomRangeFloat(5.0f, 10.0f), 0.0f);
  norm = vec2_norm(speed);

  ellipseMode(CENTER);
  textFont(defaultFont, 20);
}

void update()
{
  background(color(255, 255, 255, 255));

  // Check if direction should be inverted
  if (position.x > canvasWidth)
  {
    speed = vec2_neg(speed);
    norm = vec2_norm(speed);
    position.x = canvasWidth;
  }
  else if (position.x < 0)
  {
    speed = vec2_neg(speed);
    norm = vec2_norm(speed);
    position.x = 0;
  }

  // Update position
  position = vec2_add(position, speed);
  position2 = vec2_add(position2, norm);

  // Draw the circles
  fill(color(255, 0, 0, 255));
  circle(position.x, position.y, 40);
  fill(color(0, 0, 255, 255));
  circle(position2.x, position2.y, 40);

  // Draw the speed and normzlied speed
  char speed_text[128] = {0};
  sprintf_s(speed_text, 128, "Speed: [%.2f,%.2f] Normalized: [%.2f,%.2f]", speed.x, speed.y, norm.x, norm.y);
  fill(color(0, 0, 0, 255));
  text(speed_text, canvasWidth / 2 - 160, canvasHeight / 2);
}

Related

Personal tools
Namespaces

Variants
Actions
Navigation
NameSpaces:>
Tools
Dynamic:>