<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with mult() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=mult%28%29</link>
      <pubDate>Sun, 08 Aug 2021 19:49:00 +0000</pubDate>
         <description>Tagged with mult() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedmult%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>pointing towards mouse snippet</title>
      <link>https://forum.processing.org/two/discussion/27854/pointing-towards-mouse-snippet</link>
      <pubDate>Thu, 26 Apr 2018 08:12:46 +0000</pubDate>
      <dc:creator>appinv</dc:creator>
      <guid isPermaLink="false">27854@/two/discussions</guid>
      <description><![CDATA[<p>i have seen many un-processonic codes for dealing with pointing towards mouse including the use of atan and PVector
here is a natural solution :</p>

<pre><code>def setup():
    size(640, 640)


def draw():
    background(255)
    translate(width/2, height/2)
    location = PVector(200, 200)
    mouse = PVector(mouseX, mouseY)

    mouse.sub(location) # vector from mouse to point
    mouse.normalize()
    mouse.mult(50)
    line(0, 0, mouse.x, mouse.y)
</code></pre>
]]></description>
   </item>
   <item>
      <title>2d Metaball sketch running super slow in Python mode</title>
      <link>https://forum.processing.org/two/discussion/27651/2d-metaball-sketch-running-super-slow-in-python-mode</link>
      <pubDate>Mon, 02 Apr 2018 20:27:28 +0000</pubDate>
      <dc:creator>solub</dc:creator>
      <guid isPermaLink="false">27651@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys,</p>

<p>I made several Python versions of 2d metaball sketches I found here on the forum or on the CodingTrain Github.</p>

<p>Problem: It runs super slow (&lt;1fps !) while all Java versions run very smoothly (60fps).</p>

<p>Questions:</p>

<ul>
<li><p>Why such a difference in the framerates ?</p></li>
<li><p>Is is possible to improve the Python code or am i for ever doomed for having chosen Python mode over Java mode ?</p></li>
</ul>

<p><strong>original JAVA code</strong></p>

<p>main tab:</p>

<pre><code>Blob[] blobs = new Blob[10];

void setup() {
  size(640, 360);
  colorMode(HSB);
  for (int i = 0; i &lt; blobs.length; i++) {
    blobs[i] = new Blob(random(width), random(height));
  }
}

void draw() {
  background(51);


  println(frameRate);

  loadPixels();
  for (int x = 0; x &lt; width; x++) {
    for (int y = 0; y &lt; height; y++) {
      int index = x + y * width;
      float sum = 0;
      for (Blob b : blobs) {
        float d = dist(x, y, b.pos.x, b.pos.y);
        sum += 10 * b.r / d;
      }
      pixels[index] = color(sum, 255, 255);
    }
  }

  updatePixels();

  for (Blob b : blobs) {
    b.update();
    //b.show();
  }
}
</code></pre>

<p>blob class</p>

<pre><code>class Blob {
  PVector pos;
  float r;
  PVector vel;

  Blob(float x, float y) {
    pos = new PVector(x, y);
    vel = PVector.random2D();
    vel.mult(random(2, 5));
    r = random(120, 400);
  }

  void update() {
    pos.add(vel); 
    if (pos.x &gt; width || pos.x &lt; 0) {
      vel.x *= -1;
    }
    if (pos.y &gt; height || pos.y &lt; 0) {
      vel.y *= -1;
    }
  }

  void show() {
    noFill();
    stroke(0);
    strokeWeight(4);
    ellipse(pos.x, pos.y, r*2, r*2);
  }
}
</code></pre>

<p><strong>PYTHON code</strong></p>

<pre><code>liste = []

def setup():
    size(640, 360, FX2D)
    colorMode(HSB)
    [liste.append(Blob(random(width), random(height))) for e in range(10)]

def draw():
    loadPixels()
    for x in range(width):
        for y in range(height):
            index = x + y * width
            sum = 0
            for e in liste:
                d = dist(x, y, e.pos.x, e.pos.y)
                try:
                    sum += 10 * e.r / d
                except ZeroDivisionError:
                    return 1
            pixels[index] = color(sum, 255, 255)
    updatePixels()

    for e in liste:
        e.update()

class Blob(object):
    def __init__(self, x, y):
        self.pos = PVector(x, y)
        self.velocity = PVector.random2D()
        self.velocity.mult(random(2, 5))
        self.r = random(120, 400)

    def update(self):
        self.pos.add(self.velocity)

        if self.pos.x &gt; width or self.pos.x &lt; 0:
            self.velocity.x *= -1
        if self.pos.y &gt; height or self.pos.y &lt; 0:
            self.velocity.y *= -1
</code></pre>
]]></description>
   </item>
   <item>
      <title>Why is the result of this PVector math different than the primitive? How can I make them the same?</title>
      <link>https://forum.processing.org/two/discussion/27628/why-is-the-result-of-this-pvector-math-different-than-the-primitive-how-can-i-make-them-the-same</link>
      <pubDate>Mon, 02 Apr 2018 02:34:10 +0000</pubDate>
      <dc:creator>BGADII</dc:creator>
      <guid isPermaLink="false">27628@/two/discussions</guid>
      <description><![CDATA[<p>These two blocks of code yield radically different results. For the sake of simplicity I'm just working with the 1 dimension. Why is that?</p>

<pre><code>void PVector(){
a.add(0, 98);
v.add(a.mult(1.0/frameRate));
l.add(v.mult(1.0/frameRate)); // edit &lt;- when this happens, it's multiplying the whole vector and saving it as if it was v = v * 1/x;
a.mult(0);
}

void Primitive(){
a += 98;
v += a * (1/frameRate);
l += v * (1/frameRate);
a = 0;
}
</code></pre>

<p>You would think that the PVector l.y would be the same as the primitive float l, but it's not. Run it for a few hundred frames and they are miles apart. The primitive value advances at the correct speed, the PVector value advances very, very slowly.</p>

<p>You can see that after just 30 frames PVector l.y = 11 vs  float l = 162. PVector version is just adding by the value of acceleration *(1/frameRate). It's not accumulating to v.</p>

<pre><code>1 0.792847 0.792847
2 1.5435343 2.213922
3 2.2012308 4.1423683
4 2.7871804 6.5059586
5 3.3176618 9.250198
6 3.806187 12.342217
7 4.2596936 15.747873
8 4.683733 19.441088
9 5.0847764 23.412453
10 5.466639 27.649351
11 5.832577 32.14402
12 6.1839776 36.88176
13 6.5261645 41.88294
14 6.857661 47.11915
15 7.179004 52.57995
16 7.4931245 58.278584
17 7.800785 64.210884
18 8.10281 70.375946
19 8.400051 76.774864
20 8.692898 83.404854
21 8.981894 90.266136
22 9.267535 97.35933
23 9.550255 104.68519
24 9.831322 112.257385
25 10.109912 120.06045
26 10.386936 128.1054
27 10.660829 136.36436
28 10.931881 144.83878
29 11.201469 153.54774
30 11.471621 162.52364
</code></pre>

<p>This gives the correct output (same as primitive):</p>

<pre><code>void PVector(){
a.add(0, 98);
v.add(a.mult(1.0/frameRate));
PVector temp = new PVector();
temp.add(v);
l.add(temp.mult(1.0/frameRate));
a.mult(0);
}
</code></pre>

<p>This gives the wrong output:</p>

<pre><code>void PVector(){
a.add(0, 98);
v.add(a.mult(1.0/frameRate));
PVector temp = new PVector();
temp = v;
l.add(temp.mult(1.0/frameRate));
a.mult(0);
}
</code></pre>

<p>Does PVectorA = PVectorB mean that any changes that happen to PVectorA also apply to PVectorB? Also, can someone explain why the original with no temp pvector didn't work? It's really confusing.</p>
]]></description>
   </item>
   <item>
      <title>smooth friction until velocity gets very close to zero, then jerky for the last couple of pixels</title>
      <link>https://forum.processing.org/two/discussion/27378/smooth-friction-until-velocity-gets-very-close-to-zero-then-jerky-for-the-last-couple-of-pixels</link>
      <pubDate>Mon, 26 Mar 2018 18:01:23 +0000</pubDate>
      <dc:creator>ottenm</dc:creator>
      <guid isPermaLink="false">27378@/two/discussions</guid>
      <description><![CDATA[<p>This sketch moves the marbles when you hit the space bar.  They decelerate smoothly until almost stopped, but then jiggle just enough to bother the programmer.  It's only a couple of unstable pixels at the very end, but not the nice fluid deceleration you'd like to see (and show to your friends).
Any suggestions greatly appreciated!</p>

<pre><code>import java.util.ArrayList;

ArrayList list = new ArrayList();
float radius = 35;
float maxVelocity = 10;

void setup() {
  size(800, 600);
  smooth();
  for (int i = 0; i&lt; 15; i++)
    list.add(new Marble());
}

void draw() {
  if (millis() &lt; 1000)
    ((java.awt.Canvas) surface.getNative()).requestFocus();
  background(200);
  for (Marble m : list)
    m.draw();
}

void keyPressed() {
  for (Marble m : list)
    m.velocity.set(random(-maxVelocity, maxVelocity), random(-maxVelocity, maxVelocity));
}

class Marble {
  PVector location, velocity;

  public Marble() {
    location = new PVector(random(width*0.1, width*0.9), random(height*0.1, height*0.9));
    velocity = new PVector(random(-maxVelocity, maxVelocity), random(-maxVelocity, maxVelocity));
  }

  void draw() {
    ellipse(location.x, location.y, radius * 2, radius * 2);
    checkEdgeCollision();
    location.add(velocity);
    velocity.mult(0.975);
  }

  public void checkEdgeCollision() {
    if ((location.x &gt; width - radius) || (location.x &lt; radius)) 
      velocity.x *= -1;
    if ((location.y &gt; height - radius) || (location.y &lt; radius)) 
      velocity.y *= -1;
    if (location.x &gt; width - radius) 
      location.x = width - radius;
    else if (location.x &lt; radius) 
      location.x = radius;
    if (location.y &gt; height - radius) 
      location.y = height - radius;
    else if (location.y &lt; radius) 
      location.y = radius;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Interactive fractal tree</title>
      <link>https://forum.processing.org/two/discussion/26813/interactive-fractal-tree</link>
      <pubDate>Tue, 13 Mar 2018 20:50:55 +0000</pubDate>
      <dc:creator>BjarkePedersen</dc:creator>
      <guid isPermaLink="false">26813@/two/discussions</guid>
      <description><![CDATA[<p>Yes, it's just a regular old fractal tree. But it's pretty :)</p>

<p>Try dragging it with your mouse</p>

<pre><code>int iterations = 14;
int treeSize = floor(pow(2, iterations)-1);
Branch[] tree = new Branch[treeSize];

float t, t2, colorT;

float angle = 45;
float startangle;
float startererangle = angle;

float wind = 1;
float startwind = wind;
float tempWind;

float r, g, b;
boolean mouseBegin = true;
PVector startMouse;
float tempAngle;

float friction = 0.98; // 0.95 for original
float tension = 0.03;  // 0.1 for original

PGraphics pg;

int noiseSeed1, noiseSeed2, noiseSeed3;

int cursorCount = 0;

void setup () {
  fill(0);
  //size(800, 800, P2D);
  fullScreen(OPENGL);
  pixelDensity(displayDensity());
  smooth(8);
  pg = createGraphics(width, height);

  for (int i=1; i&lt;treeSize; i++) {
    tree[i] = new Branch(new PVector(0,0),new PVector(0,0));
  }
  seed();
  plant();

  noiseSeed1 = day() + hour() + minute() + second();
  noiseSeed2 = int(noiseSeed1 * 1.41421356237);
  noiseSeed3 = int(noiseSeed2 * 3.14159265358);

}

void seed() {
  PVector dir = new PVector(0, -300);
  dir.rotate(rad(wind));

  PVector a = new PVector(width/2, height-100) ;
  PVector b = new PVector(width/2+dir.x, height+dir.y-100);
  tree[0] = new Branch(a, b);
}


void plant() {
  seed();

  for (int i=1; i&lt;treeSize; i++) {
    int n = floor((i-1)/2);
    if (i % 2 == 0) {
      tree[n].branch(-1, tree[i]);
    } else {
      tree[n].branch(1, tree[i]);
    }
  }
}

void physics() {
  wind = startwind*(cos(t))*-1;
  startwind *= friction;
  noiseSeed(1337);
  startwind += map(noise(t/51-100), 0, 1, -0.2, 0.2);
  t -= tension;

  angle = startererangle + startangle*(cos(t2));
  startangle *= friction;
  noiseSeed(42);
  startangle += map(noise(t2/50), 0, 1, -0.2, 0.2);
  t2 -= tension;
}

PVector prevMouse, mouse;

void mouse(){
  // Hide / show cursor
  prevMouse = mouse!=null ? mouse : new PVector(mouseX, mouseY);
  mouse = new PVector(mouseX, mouseY);
  cursorCount ++;
  if (mouse.x != prevMouse.x || mousePressed) {cursorCount = 0; cursor();};
  if (cursorCount &gt; 20) noCursor();

  if (!mousePressed) {
      physics();
      mouseBegin = true;
    } else {
      if (mouseBegin == true) {
        startMouse = new PVector(mouseX, mouseY);
        tempWind = wind;
        tempAngle = angle;
        mouseBegin = false;
      }
      wind = tempWind + map(mouseX-startMouse.x, -width, width, deg(-1), deg(1));
      startwind = abs(wind);
      t = abs((wind/abs(wind)+1)*PI/2);

      angle = abs(tempAngle + map(mouseY-startMouse.y, -height, height, deg(-1), deg(1)))+0.01;
      startangle = startererangle-angle;
      t2 = abs(((angle/abs(angle)+1))*PI/2);
    }
}

void draw() {
  //println(frameRate);
  mouse();
  plant();

  noiseSeed(noiseSeed1);
  float r = map(noise(colorT/50), 0, 1, 0, 255);
  noiseSeed(noiseSeed2);
  float g = map(noise(colorT/75), 0, 1, 0, 255);
  noiseSeed(noiseSeed3);
  float b = map(noise(colorT/100), 0, 1, 0, 255);
  colorT--;


  // Start drawing image
  background(25);

  stroke(r, g, b);
  fill(r, g, b);
  rect(width/2-20, height-100, 40, 20, 3, 3, 40, 40);

  int level = 1;

  for (int i=0; i&lt;treeSize; i++) {
    if ((i % (pow(2, level)-1)) == 0) {
      //if (level &gt; 6) strokeWeight(1);
      strokeWeight((iterations-level)/2);

      noiseSeed(noiseSeed1);
      r = map(noise(colorT/50+level*0.2), 0, 1, 0, 255);
      noiseSeed(noiseSeed2);
      g = map(noise(colorT/75+level*0.2), 0, 1, 0, 255);
      noiseSeed(noiseSeed3);
      b = map(noise(colorT/100+level*0.2), 0, 1, 0, 255);

      stroke(r, g, b);

      level++;
    }
    tree[i].show();
  }
}

public class Branch {
  PVector begin;
  PVector end;
  float rand;
  boolean finished = false;
  float rotation = 0;

  public Branch(PVector begin, PVector end) {
    this.begin = begin;
    this.end = end;
  }

  public void show() {
    line(this.begin.x, this.begin.y, this.end.x, this.end.y);
  }

  public void branch(int direction, Branch targetBranch) {
    PVector dir = new PVector(this.end.x-this.begin.x, this.end.y-this.begin.y);
    dir.rotate(rad(direction*angle+wind));
    dir.mult(0.6667);
    PVector newEnd = new PVector(this.end.x+dir.x, this.end.y+dir.y);
    targetBranch.begin = this.end;
    targetBranch.end = newEnd;
  }
}

static float rad(float deg) {
  return deg*PI/180;
}

static float deg(float rad) {
  return rad*180/PI;
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Simulating Gravity accurately</title>
      <link>https://forum.processing.org/two/discussion/24499/simulating-gravity-accurately</link>
      <pubDate>Wed, 11 Oct 2017 21:41:00 +0000</pubDate>
      <dc:creator>lorensheets</dc:creator>
      <guid isPermaLink="false">24499@/two/discussions</guid>
      <description><![CDATA[<p>Hello!</p>

<p>I'm <em>relatively</em> new to p5.js, and have been working on a physics simulation where I want to accurately simulate gravity in a window that allows for scaling units.</p>

<p>The problem I had was scaling such that I could set my gravity.y vector to 9.8, and have 1 meter = 1 pixel, such that the object accelerates down at 9.8px/x^2. However, at a frameRate of 60, there's problems. I discovered that I had to do G.mult(someFactor) to make it accurate. Here's the formula that made it work:</p>

<pre><code>function fS(n) {
  total = 0;
  for (var i = 0; i &lt;= n; i++) {
    total += i;  
  }
  return 1/(total*2);
}        

someFactor = fS( frameRate() );
</code></pre>

<p>I also have a simScale variable that changes the meters/pixels ratio, and currently it's messing up the physics i.e it only produces the right outputs when its equal to 1 (1m = 1px). Here's the entire code, looking for suggestions as to how to improve.</p>

<p>=======================================</p>

<pre><code>function fS(n) {
  total = 0;
  for (var i = 0; i &lt;= n; i++) {
    total += i;  
  }
  return 1/(total*2);
}

function setup() {
  counter = 0;
  fR = 60;
  frameRate(fR);
  W = windowWidth;
  H = windowHeight;
  ground = H;
  simScale = 1;
  frameScale = fS(fR);
  G = createVector(0, 9.8);
  G.mult(simScale);


  createCanvas(W, H);
  ball = new Ball();
}

function draw() {
  background(2);
  ball.show();
  counter++;
}


function Ball() {

  this.r = 10; 

  this.dropHeight = 123    // height in meters you want to drop from

  this.initHeight = ground - this.dropHeight - this.r; 
  this.pos = createVector(0, this.initHeight / simScale);
  this.acceleration = createVector(0, 0);
  this.velocity = createVector(0, 0);
  this.altitude = ground - this.pos.y - this.r;

  this.updatePos = function() {
    var scaledG = p5.Vector.mult(G, frameScale); 
    this.acceleration.add(scaledG);  
    this.velocity.add(this.acceleration);
    this.pos.add(this.velocity);
    if (this.pos.y &gt; ground - this.r) {  
      this.pos.y = ground - this.r;  
      noLoop();
    }
    this.altitude = ground - this.pos.y - this.r;
    this.acceleration.mult(0); 
  }

  this.show = function() {
    this.updatePos();
    ellipse(W/2, this.pos.y, this.r*2, this.r*2); 
    fill(200);
    text("Scale: 1m = " + simScale + " px(s)", 200, 30);
    text("Altitude: " + (this.altitude/simScale).toFixed(2) + " m", 20, 30);
    text("Elapsed: " + (counter/fR).toFixed(2) + " s", 20, 50);
    text("Displacement: " + Math.abs(this.initHeight - this.pos.y).toFixed(2) + " m", 20, 70);
    text("Velocity: " + (this.velocity.y * fR).toFixed(2) + " m/s", 20, 90);  
  }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Having a vector maintain position once it hits ground.</title>
      <link>https://forum.processing.org/two/discussion/22690/having-a-vector-maintain-position-once-it-hits-ground</link>
      <pubDate>Sun, 21 May 2017 03:18:20 +0000</pubDate>
      <dc:creator>ex080</dc:creator>
      <guid isPermaLink="false">22690@/two/discussions</guid>
      <description><![CDATA[<p>Hi, 
I'm trying to create a bow and arrow simulator, it's very much in the early stages. Right now I can launch little rectangles out from a launch point, but when they hit the ground they lay flat. I would like the rectangle to maintain the same angle and position as when it hits the ground. (think of a arrow embedding itself into the ground.)</p>

<p>there are only two vectors involved, gravity and the launch vector.  Right now when the rectangle reaches y=350 I multiply the vel and acc by 0 and set the pos.y to the ground's y value.</p>

<p>this is a gif. 
<img src="https://forum.processing.org/two/uploads/imageupload/685/MM4ZF45POI0X.gif" alt="arrow launch" title="arrow launch" /></p>

<pre><code>function Projectile(apos, angle, power) {

this.pos = createVector(apos.x,apos.y);
this.vel = p5.Vector.fromAngle(angle-(PI));
this.vel.mult(power/15);
this.acc = createVector(0,0);
this.applyForce = function(force){
this.acc.add(force);
}
this.update = function() {
this.vel.add(this.acc);
this.pos.add(this.vel);
this.acc.mult(0);
if (this.pos.y &gt; 350){
  this.pos.y = 350;
  this.acc.mult(0);
  this.vel.mult(0);
}
}
this.render = function(){
  push();
    translate(this.pos.x,this.pos.y);
    rectMode(CENTER);
    rotate(this.vel.heading());
    fill(255);
    rect(0,0, 10, 6);
  pop();
}
}
</code></pre>

<p>P.S. I tried formatting the code, but it wasn't working. I feel like a noob.</p>
]]></description>
   </item>
   <item>
      <title>Zooming in and out using the direction keys? / Changing color of text</title>
      <link>https://forum.processing.org/two/discussion/19076/zooming-in-and-out-using-the-direction-keys-changing-color-of-text</link>
      <pubDate>Wed, 16 Nov 2016 19:23:20 +0000</pubDate>
      <dc:creator>drewk94</dc:creator>
      <guid isPermaLink="false">19076@/two/discussions</guid>
      <description><![CDATA[<p>Hello! Really new to processing.. new to programming in general so bear with me. All I want to do is:</p>

<p>1) Change the color of the text
<br />
2) Zoom in and out using the directional keys (Up, down, left, right)</p>

<p>I can't manage to figure it out.. some help would be great. 
Thank you.</p>

<pre><code>TextGraphics tg;
PVector root = new PVector(random(1234), random(1234), random(1234)), //noise root
nSpeed = new PVector(random(-.02, .02), random(-.02, .02), random(-.02, .02));//noise speed;
ArrayList&lt;Particle&gt; particles = new ArrayList&lt;Particle&gt;();
int nbParticle = 6000;
int[] pgpx;//PGraphics' pixels array
float zoom = 100;//noise zoom level
Boolean noiseOn = true, hitMode = true;
import peasy.*;
PeasyCam cam;


void setup()
{
  size(1300, 800, P3D);
  cam = new PeasyCam(this, 800);
  cam.setMinimumDistance(50);
  cam.setMaximumDistance(1300);
  tg = new TextGraphics();
  strokeWeight(10);
  smooth();

}

void draw()
{ 
  background(0);
  lights();
  box(0);
  pushMatrix();
  box(0);
  popMatrix();


  for (int i = 0; i &lt; nbParticle; i++)
  {
    Particle p = particles.get(i);
    p.update();
  }
  root.add(nSpeed);//update noise


}


void createParticles()
{
  particles = new ArrayList&lt;Particle&gt;();
  //random particle disposition 
  while (particles.size () &lt; nbParticle)
  {
    Particle p = new Particle(particles.size ());
    particles.add(p);
  }
}

void mousePressed()
{
  root = new PVector(random(1234), random(1234));//reset noise root
  nSpeed = new PVector(random(-.02, .02), random(-.02, .02));//reset noise speed
}

void keyPressed()

  {
    switch(key)
    {
    case 'n'://noise toggle
      noiseOn = !noiseOn;
      break;
    case 'h'://hit toggle
      hitMode = !hitMode;
      if (!hitMode)
        for (Particle p : particles)
        {
          p.speed.mult(-1);
        }
      break;
    case ' '://ignore SPACE
    case ESC://ignore ESCAPE
    case ENTER://ignore ENTER
    case BACKSPACE://ignore BACKSPACE
      break;
    default://char input
      //tg.process("" + key);//RUN IN JAVA

      break;
    }
  }


class Particle
{
  final float SPEED_MIN = .12, SPEED_MAX = .25, h = 40;
  PVector pos, origin, speed;
  int rank, col = color(random(128, 255), random(128, 205), 90, 120);
  float n, nz;//noise
  Boolean stuck = false;//against a wall

  Particle(int p_rank)
  {
    rank = p_rank;
    init();
  }

  void init()
  {
    stuck = false;
    float theta = random(TWO_PI);
    speed = new PVector(cos(theta), sin(theta), -cos(theta));
    speed.mult(random(SPEED_MIN, SPEED_MAX) * (random(1)&lt;0?1:-1));
    Boolean done = false;
    while (!done)
    {
      pos = new PVector(random(width), random(height));
      if (green(pgpx[(int)pos.y * width + (int)pos.x]) &gt; 100)
      {
        pos.z = random(-h/2, h/2);
        origin = pos.get();
        done = true;
      }
    }
  }

  void update()
  {
    if (noiseOn &amp;&amp; !stuck)
    {
      n = noise(root.x + pos.x/zoom, root.y + pos.y/zoom, root.z + pos.z/zoom)*2*TWO_PI;
      nz = noise(root.x/10 + pos.x/zoom, root.y + pos.y/zoom, root.z + pos.z/zoom)*2*TWO_PI;
      speed.set(cos(n), sin(n), -cos(nz));
      speed.mult(SPEED_MAX);
    }

    if (!(stuck &amp;&amp; hitMode))
      pos.add(speed);

    if (green(pgpx[(int)pos.y * width + (int)pos.x]) &lt; 80)//particle outside the letter
    {
      stuck = hitMode;
      pos.sub(speed);
      if (!hitMode)
      {
        if (noiseOn)
        { 
          pos = origin.get();
        } else
        {      
          speed.x *= -1;
          speed.y *= -1;
        }
      }
    }
    if (pos.z &gt; h/2 || pos.z &lt; -h/2)
    {
      stuck = hitMode;
      pos.z = constrain(pos.z, -h/2, h/2);
      if (!hitMode)
      {
        if (noiseOn)
        {
          pos = origin.get();
        } else
        {
          speed.z *= -1;
        }
      }
    }

    stroke(map(pos.z, -h/2, h/2, 128, 255), map(pos.z, -h/2, h/2, 128, 205), 90, 120);
    point(pos.x-width/2, pos.y-height/2, pos.z);
  }
}

class TextGraphics
{  
  PGraphics pg;//buffer PG used to write the input char

  TextGraphics()
  {
    pg = createGraphics(width, height, P2D);
    process(new String("Nothing is ever complete."));//"Ï�")//initialize with a String
  }

  void process(String c)
  {
    pg.beginDraw();
    pg.translate(-width/2, -height/1.7);
    pg.background(0);
    pg.textSize(70);//500
    pg.fill(color(255, 255, 255));
    pg.textAlign(CENTER, CENTER);
    pg.text(c, width, height);
    pg.translate(width/2, height/1.7);
    pg.endDraw();

    pgpx = new int[width * height];
    pg.loadPixels();
    arrayCopy(pg.pixels, pgpx);
    pg.updatePixels();

    createParticles();
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>PVector feature request</title>
      <link>https://forum.processing.org/two/discussion/18600/pvector-feature-request</link>
      <pubDate>Mon, 17 Oct 2016 21:54:59 +0000</pubDate>
      <dc:creator>willemkempers</dc:creator>
      <guid isPermaLink="false">18600@/two/discussions</guid>
      <description><![CDATA[<p>See this thread: <a href="https://forum.processing.org/two/discussion/18585/multiplying-vectors#latest" target="_blank" rel="nofollow">https://forum.processing.org/two/discussion/18585/multiplying-vectors#latest</a></p>

<p>Would be great to have 'PVector.convolute()' implemented, as <a href="/two/profile/jeremydouglass">@jeremydouglass</a> suggested.</p>

<p>Basically, a function that multiplies the individual fields of two PVectors (x1 * x2, y1 * y2, z1 * z2) and returns a new PVector.</p>

<p>Thanks!</p>
]]></description>
   </item>
   <item>
      <title>Multiplying vectors</title>
      <link>https://forum.processing.org/two/discussion/18585/multiplying-vectors</link>
      <pubDate>Sun, 16 Oct 2016 21:37:04 +0000</pubDate>
      <dc:creator>willemkempers</dc:creator>
      <guid isPermaLink="false">18585@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>Everytime I want to do multiplications on PVectors I get frustrated as PVector.mult(PVector) doesn't exist. I've seen one or two threads on the forums about this, so I know that it apparently doesn't make much sense. Can someone point me to the correct way of multiplying a normalised position PVector with a pixel space PVector?</p>

<p>Say I have this:</p>

<p><code>PVector pixelSpaceSize = new PVector(400, 300);
PVector normalizedPosition = new PVector(0.8, 0.2);</code></p>

<p>And I want to get the pixel space position of my normalised position? Ideally I'd do...</p>

<p><code>PVector pixelPosition = PVector.mult(pixelSpaceSize, normalizedPosition);</code></p>

<p>Right? But instead I now have to multiply the individual fields:</p>

<p><code>PVector pixelPosition = PVector.mult(pixelSpaceSize.x * normalizedPosition.x, pixelSpaceSize.y * normalizedPosition.y, pixelSpaceSize.z * normalizedPosition.z);</code></p>

<p>I'm sure there's a very good reason why this is not-done, but how should I approach this? Stick to the incredibly long x * x, y * y and z * z or is there some other method?</p>

<p>Many thanks</p>
]]></description>
   </item>
   <item>
      <title>NaN return in code when computing normal vector</title>
      <link>https://forum.processing.org/two/discussion/17622/nan-return-in-code-when-computing-normal-vector</link>
      <pubDate>Sat, 23 Jul 2016 02:16:41 +0000</pubDate>
      <dc:creator>nuh</dc:creator>
      <guid isPermaLink="false">17622@/two/discussions</guid>
      <description><![CDATA[<p>Hey im having trouble figuring out why my code returns NaN when i set m=0 or when i give it the angle =0 . Help would be greatly appreciated i've been trying to figure this out for a while now.</p>

<pre><code>    PVector nvector(float angle){
      float sinc = (m/8)*sin((m/2)*angle);
      float cosc= ((pow(m,2))/16)*cos((m/2)*angle); 

      float g =(-n2*pow(abs(1/a),n2))*pow(cos((m/4)*angle),n2-2)
        +(n3*pow(abs(1/b),n3))*pow(sin((m/4)*angle),n3-2) ;

      float dg = (n2*pow(abs(1/a),n2))*((n2-2))*sinc*pow(cos((m/4)*angle),n2-4)
        +(n3*pow(abs(1/b),n3))*((n3-2))*sinc*pow(sin((m/4)*angle),n3-4);

      float f = pow(abs((1/a)*cos((m/4)*angle)),n2)+ pow(abs((1/b)*sin((m/4)*angle)),n3);

      float df = sinc*g ;

      float d2f = dg*sinc+g*cosc ; 

      float r =pow(f,(-1/n1)); // this is taken care of by the shape function
      float dr = (-1/n1)*pow(f,((-1/n1)-1))*df;

      float d2r =  (1/n1)*((1/n1)+1)*pow(f,((-1/n1)-2))*pow(df,2)+(-1/n1)*pow(f,(-1/n1)-1)*d2f;

      PVector v1 = new PVector(cos(angle),sin(angle)); 
      PVector v3 = new PVector(cos(angle),sin(angle));
      PVector v2 = new PVector(-sin(angle),cos(angle));

      v1.mult(d2r);
      v2.mult((2*dr));
      v3.mult(r);

      PVector M = v1.add(v2);
      PVector N = M.sub(v3);

       return N;
    } 
</code></pre>
]]></description>
   </item>
   <item>
      <title>Multiply two PVectors</title>
      <link>https://forum.processing.org/two/discussion/17482/multiply-two-pvectors</link>
      <pubDate>Mon, 11 Jul 2016 13:50:30 +0000</pubDate>
      <dc:creator>eightohnine</dc:creator>
      <guid isPermaLink="false">17482@/two/discussions</guid>
      <description><![CDATA[<p>Hi all!</p>

<p>I've stumbled across an interesting looking sketch on OpenProcessing, but since it's several years old, I'm having a hard time updating some of the legacy code. More specifically, I'm struggling with this line of code:</p>

<p><code>if (t[j]==null) t[j]   = PVector.mult(v[j],textureScale);</code></p>

<p>The error I get is</p>

<p><code>The method mult(PVector, float) in the type PVector is not applicable for the arguments (PVector, PVector)</code></p>

<p>After looking into the reference, I know the issue concerns the right part of the line and is that the mult() method for PVector no longer takes two vectors – v[j] and textureScale both are PVectors – as arguments, but now it expects one vector and one float (the scalar).</p>

<p>This is all fine and good, but I can't for the life of me figure out how to replicate the simple multiplication of two vectors.  I'm not really fluent in vector math and upon googling have found things called the cross or dot product, but using those doesn't yield the results I'm looking for.</p>

<p>Does anyone know how I can recreate the "old" code but with current Processing syntax? Thanks for any hints!</p>
]]></description>
   </item>
   <item>
      <title>Is there a formula to place objects 3d in a radial way, like forming a sphere?</title>
      <link>https://forum.processing.org/two/discussion/17032/is-there-a-formula-to-place-objects-3d-in-a-radial-way-like-forming-a-sphere</link>
      <pubDate>Tue, 07 Jun 2016 23:58:29 +0000</pubDate>
      <dc:creator>Rhorek</dc:creator>
      <guid isPermaLink="false">17032@/two/discussions</guid>
      <description><![CDATA[<p>Hey, I'm struggling to find a way to place instances of a class into an array in such way that being radial so form a sphere, I think it would look somewhat like this, but along all the surface of the sphere, I tried using the cos and sin into the position variables of the vertex of the  QUAD_STRIP with no success. Thanks in advance guys.<img src="http://www.digicult.it/wp-content/uploads/2010/09/numero57_Generative-Pratice-09.png" alt="" /></p>
]]></description>
   </item>
   <item>
      <title>scale and movement when mouse over</title>
      <link>https://forum.processing.org/two/discussion/16895/scale-and-movement-when-mouse-over</link>
      <pubDate>Mon, 30 May 2016 09:49:56 +0000</pubDate>
      <dc:creator>georges4242</dc:creator>
      <guid isPermaLink="false">16895@/two/discussions</guid>
      <description><![CDATA[<p>Hi !</p>

<p>I have a problem, I would like that when i put my mouse over my sketche, it make an effect like this web site <a href="http://veille.reputationsquad.com/#accueil" target="_blank" rel="nofollow">http://veille.reputationsquad.com/#accueil</a>  (scale and movement). i have found different example in different forum but all doesn't work. i know the different function like mouseover, scale but i don't know how to use them :s</p>

<p>thanks a lot for your help</p>

<p>emilie</p>

<p>There is my code :</p>

<blockquote class="Quote">
  <p>Particle[] pArray;</p>
</blockquote>

<p>void setup() {</p>

<pre><code>size( 1000, 500,P3D);           
smooth(4);            
strokeWeight(1);  
stroke(0, 2, 120); 


pArray = new Particle[2000];   


for( int i=0; i&lt;pArray.length; i++ )
{
    pArray[i] = new Particle( random( width ), random( height ), 0 );
    pArray[i].vel.set( 0, 0, 0);
}
</code></pre>

<p>}</p>

<p>void draw()  {</p>

<pre><code>background(255);
fill(0);
stroke(0, 70);
strokeWeight(1);

for ( int i=0;i&lt;pArray.length;i++ )    {       pArray[i].update();       }



for (int i = 0; i &lt; pArray.length-1; i++) {
  for (int j = i; j &lt; pArray.length; j++) {
    if (dist(pArray[j].pos.x, pArray[j].pos.y, pArray[i].pos.x, pArray[i].pos.y) &lt; 33) {
      line(pArray[j].pos.x, pArray[j].pos.y, pArray[i].pos.x, pArray[i].pos.y);
    }
  }
}
</code></pre>

<p>for ( int i=0;i&lt;pArray.length;i++ )     {        pArray[i].draw();     }</p>

<p>}</p>

<p>class Particle {</p>

<pre><code>PVector pos;    // pos.x pos.y pos.z
PVector vel;    // vel.x vel.y vel.z
PVector acc;    // acc.x acc.y acc.z



Particle( float x, float y, float z )
{

    pos = new PVector(x, y, z);   
    vel = new PVector();
    acc = new PVector();

}

//acceleration velocité
void update()
{

    vel.add( acc );              
    pos.add( vel );               
    vel.mult( 0.80f );            

    acc.set( 0, 0, 0 );          
}  
</code></pre>

<p>//particules creation</p>

<pre><code>void draw() {

    colorMode( RGB, 255, 255, 255 );    
    ellipse( pos.x, pos.y, 4, 4 );   
    point(pos.x, pos.y);
}  
</code></pre>

<p>}</p>
]]></description>
   </item>
   <item>
      <title>Ball class mover</title>
      <link>https://forum.processing.org/two/discussion/17006/ball-class-mover</link>
      <pubDate>Mon, 06 Jun 2016 15:15:51 +0000</pubDate>
      <dc:creator>sofia</dc:creator>
      <guid isPermaLink="false">17006@/two/discussions</guid>
      <description><![CDATA[<p>Hey guys! I'm quite new to processing, so I was wondering if you could help me. 
I'm trying to make a project where everytime you click on the window a new ball is launched. I already managed to do that with just one ball, but the idea is to have a new ball everytime I click. How can I do that in order to get all the balls registered on the screen? 
I'll send you the code that I already have.</p>

<pre><code>PVector location;
PVector velocity;
PVector acceleration;
PVector gravity;
PVector lance;
float friction ;
int depth;

void setup() {
  size(800, 800, P3D);
  depth = 800;
  smooth();
  background(0);
  camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / 180.0), width/2.0, height/2.0, 0, 0, 1, 0);
  gravity = new PVector(0, 0.98, 0);
  location = new PVector(width/2, height/2, -3000);
  velocity = new PVector(0, 20, -20);
  lance = new PVector(0, 0, 0);
  friction = 1.0; //0.98;
}


void draw() { 
  noStroke();
  fill(0);
  rect(0, 0, width, height);

  if (mousePressed) {
  location = new PVector(mouseX, mouseY, 200);
  lance = new PVector (0, -20, -9);
  velocity = new PVector(0, 0, 0);
}

  velocity.add(lance);
  lance = new PVector(0, 0, 0);

  if ((location.z &lt; 30)) {
  friction = 0.76;
  gravity = new PVector(0, 0, 0);
  } else {
  friction = 1.0;
  gravity = new PVector(0, 0.98, 0);
  }
  velocity.add(gravity);
  velocity.mult(friction);
  location.add(velocity);

  println(location.z);

  noStroke();
  fill(255);
  lights();
  translate(location.x, location.y, location.z);
  sphere(35);
}
</code></pre>

<p>The idea is to have something like this:</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/573/0LDAHG6UPLZC.png" alt="postal-_3-01-2" title="postal-_3-01-2" /></p>

<p>Thanks in advanced</p>
]]></description>
   </item>
   <item>
      <title>nature of code exercise 1.4</title>
      <link>https://forum.processing.org/two/discussion/16907/nature-of-code-exercise-1-4</link>
      <pubDate>Mon, 30 May 2016 21:42:54 +0000</pubDate>
      <dc:creator>cadavara</dc:creator>
      <guid isPermaLink="false">16907@/two/discussions</guid>
      <description><![CDATA[<p>I was following this book example and they gave this little exercise and I cant figure out what I’m supposed to do and the book never gives the solution.</p>

<p>how do I calculate the limit of a vector? here is the exercise.</p>

<pre><code>void limit(float max) {
  if (_______ &gt; _______) {
    _________();
    ____(max);
  }
}
</code></pre>

<p>i am trying to accomplish something like this</p>

<p>velocity.add(acceleration);<br />
velocity.limit(topspeed);</p>

<p>to get some background here is the link to said exercise.
<a href="http://natureofcode.com/book/chapter-1-vectors/" target="_blank" rel="nofollow">http://natureofcode.com/book/chapter-1-vectors/</a></p>

<p>ANSWER EDIT:</p>

<pre><code>void limitt(float max){
    if(max &gt; 10){
      velocity.normalize();
      velocity.mult(max);
    }
  }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Movement "lagging" VS smoothness</title>
      <link>https://forum.processing.org/two/discussion/16866/movement-lagging-vs-smoothness</link>
      <pubDate>Sat, 28 May 2016 17:40:18 +0000</pubDate>
      <dc:creator>strinda</dc:creator>
      <guid isPermaLink="false">16866@/two/discussions</guid>
      <description><![CDATA[<p>I am mnodeling an aircraft. For now I would like to put aside the physics part of the program. However, I have the following issue - it is as if the object is not moving smoothly but rather in steps that I can notice. May be it is just me, but maybe there are other things I do not consider.</p>

<pre><code>PVector velocity, acceleration, location;
PVector friction; //the force of friction
PVector fricAcc; // the acc due to friction

float k = 0.03; // the coeff of friction
float angle = 2; //the step with which the angle is changed

float mass = 1; //the mass
float maxEngineForce = 0.1; //the masimum frust force


void setup() {
  frameRate (70); //have no idea whether this part works at all

  location     = new PVector (100,100);
  velocity     = new PVector (0,0);
  acceleration = new PVector (0,maxEngineForce/mass);

  friction = new PVector (0,0);
  fricAcc = new PVector (0,0);

  size (1000,1000);

}

void draw () {
background (40);

fill (50);
ellipse (location.x, location.y, 50,50);

//calculating movement
location.add (velocity);
velocity.add (acceleration);


//calculating the force of friction F = -kv
friction.set (-velocity.x, -velocity.y);
friction.mult (k);

//calculating the acc due to friction a = F/m
fricAcc.set (friction.x, friction.y);
fricAcc.mult (1/mass);
velocity.add (fricAcc);

//showing the vector of acceleration
 pushMatrix ();
     translate (location.x, location.y);
     PVector show = new PVector (acceleration.x, acceleration.y);
     show.mult (1000);

     line (0,0, show.x, show.y);
 popMatrix(); 

}

//changing the direction of the acceleration
void keyPressed () {

  if (key == 'w') {
  }

  if (key == 'a') {
  acceleration.rotate (radians(angle));
  }

  if (key == 'd') {
  acceleration.rotate (radians(-angle));
  }

println (angle); //needed for debugging

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Declaring Objects</title>
      <link>https://forum.processing.org/two/discussion/14650/declaring-objects</link>
      <pubDate>Thu, 28 Jan 2016 17:14:53 +0000</pubDate>
      <dc:creator>chrisgoc</dc:creator>
      <guid isPermaLink="false">14650@/two/discussions</guid>
      <description><![CDATA[<p>Hello,</p>

<p>I'm currently reading <em>The Nature of Code</em> and I noticed that in some of the examples PVector is defined in draw. Take Example 1.4:</p>

<pre><code>void setup() {
    size(640,360);
}

void draw() {
    background(255);

    PVector mouse = new PVector(mouseX,mouseY);
    PVector center = new PVector(width/2,height/2);
    mouse.sub(center);

    //Multiplying a vector! The vector is now half its original size (multiplied by 0.5).
    mouse.mult(0.5);

    translate(width/2,height/2);
    line(0,0,mouse.x,mouse.y);

}
</code></pre>

<p>I've been using Processing for a while but I'm not a Java expert. I was wondering if the compiler does something to save the PVector because it seems like declaring new ones in each draw frame would be really inefficient.</p>

<p>Generally I layout my sketches like this:</p>

<pre><code>MyObject myObject;
PVector myPVector;

void setup() {
    myObject = new myObject();
    myPVector = new PVector();
}

void draw() {
    myObject.update();
    myPVector.update();
}
</code></pre>

<p>In general, is it costly to define objects in draw? I know that I gained a lot of speed in an Android game I made just by replacing ArrayLists with arrays of game objects so I figured it would be.</p>
]]></description>
   </item>
   <item>
      <title>Tangent vector in 3D</title>
      <link>https://forum.processing.org/two/discussion/14428/tangent-vector-in-3d</link>
      <pubDate>Wed, 13 Jan 2016 15:34:43 +0000</pubDate>
      <dc:creator>Stanlepunk</dc:creator>
      <guid isPermaLink="false">14428@/two/discussions</guid>
      <description><![CDATA[<p>Hello, 
I try to found the vector direction of tangent in 3D, but I'm locked. I find a path on internet but no one give me the solution.
<a href="http://stackoverflow.com/questions/26164521/how-is-calculating-the-unit-tangent-vector-of-a-normal-vector-in-3d" target="_blank" rel="nofollow">http://stackoverflow.com/questions/26164521/how-is-calculating-the-unit-tangent-vector-of-a-normal-vector-in-3d</a>
<a href="http://stackoverflow.com/questions/5928490/how-to-calculate-tangents-of-a-circle-in-3d" target="_blank" rel="nofollow">http://stackoverflow.com/questions/5928490/how-to-calculate-tangents-of-a-circle-in-3d</a>
<a href="http://blog.db-in.com/calculating-normals-and-tangent-space/" target="_blank" rel="nofollow">http://blog.db-in.com/calculating-normals-and-tangent-space/</a></p>

<p>I find a story about the cross product but I don't find the other vector to put in cross(Vec 1, vec2)  :(</p>

<pre><code>PVector dir, tan ;
void setup() {
  size(400,400,P3D) ;

  dir = new PVector(random(-1,1),random(-1,1),random(-1,1)) ;

  tan = new PVector() ;
  tan = dir.cross(new PVector(-dir.y, dir.x,0)) ;
}


void draw() {
  background(0) ;
  noFill() ;
  stroke(255) ;
  strokeWeight(1) ;
  int radius = 50 ;
  PVector final_pos = new PVector(width/2,height/2, 0) ;

  PVector pos_projection = new PVector() ;
  PVector dir_temp = dir.copy() ;
  pos_projection = dir_temp.mult(radius).add(final_pos).copy() ;

  PVector pos_tan = new PVector() ;
  PVector tan_temp = tan.copy() ;
  pos_tan = tan_temp.mult(radius/2).add(final_pos).copy() ;

  //display projection
  line(final_pos.x,      final_pos.y,       final_pos.z,
       pos_projection.x, pos_projection.y,  pos_projection.z ) ;
  // display tangent   
  line(pos_projection.x, pos_projection.y,  pos_projection.z,
        pos_tan.x, pos_tan.y,  pos_tan.z ) ;

  println(final_pos.x,      final_pos.y,       final_pos.z,
       pos_projection.x, pos_projection.y,  pos_projection.z ) ;

  println(pos_projection.x, pos_projection.y,  pos_projection.z,
        pos_tan.x, pos_tan.y,  pos_tan.z ) ;

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Reducing the size of a vector</title>
      <link>https://forum.processing.org/two/discussion/13285/reducing-the-size-of-a-vector</link>
      <pubDate>Mon, 26 Oct 2015 18:32:29 +0000</pubDate>
      <dc:creator>CharlesDesign</dc:creator>
      <guid isPermaLink="false">13285@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>I've created a grid of eyes and I'm trying to get each pupil to follow the mouse without it coming out of the ellipse.
As I understand multiplying the vector by a factor of 0.5 would half the size of my line, unfortunately this is not the case.</p>

<p>Could anyone help me out?!</p>

<p>Thanks :)</p>

<p>Ps: Of course, if there's is a more efficient way of doing this please feel free to point it out.</p>

<pre><code>int nEyes = 20;
PVector[] eyes = new PVector[nEyes*5];
PVector[] mouse = new PVector[nEyes*5];

void setup() {
  size(600, 400);
  noFill();
  smooth();

  // Creating an array of points
  int i = 0;
  for (int x = 1; x &lt; nEyes; x++) {
    for (int y = 1; y &lt; nEyes; y++) {
      eyes[i] = new PVector((width/nEyes) * x, (height/nEyes) * y);
      y ++;
      i ++;
    }
    x ++;
  }
}

void draw() {

  background(255);

  for (int i = 0; i &lt; eyes.length; i++) {
    noFill();
    ellipse(eyes[i].x, eyes[i].y, 50, 25); // This is the eye

    mouse[i] = new PVector(mouseX, mouseY);

    //mouse[i].sub(eyes[i]); // These won't work
    //mouse[i].mult(0.1);
    //mouse[i].limit(20);


    fill(0);
    ellipse(mouse[i].x, mouse[i].y, 10, 10); // This is the pupil
    line(eyes[i].x, eyes[i].y, mouse[i].x, mouse[i].y);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Programming with Vectors (Objects moving towards each other)</title>
      <link>https://forum.processing.org/two/discussion/11249/programming-with-vectors-objects-moving-towards-each-other</link>
      <pubDate>Wed, 10 Jun 2015 13:14:02 +0000</pubDate>
      <dc:creator>Bakafly</dc:creator>
      <guid isPermaLink="false">11249@/two/discussions</guid>
      <description><![CDATA[<p>I want to simulate a river stream eventually. That means I want to have a board with a vector in each field. 
 For now I'm trying to make the "red dots" go towards random vectors. Well, I know how to make the dots follow the mouse but not the vectors. I'd also like to visualize the vectors as black circles (for now, so i can check their position visually).
I also used to have a vector class, where i already visualized the vectors as i wished to. Though it was an Array List and absolute -&gt; not ideal for my goal. So i cut it out for now.</p>

<p>Thank you in advance :)</p>

<p>Here is my code:</p>

<pre><code>ArrayList mikroplastikParticles; // set of Mikroplastik Particles
int numOfMikroplastikPerField = 1;
int boardSize = 7; // board to be filled with vectors
int board [][] = new int [boardSize][boardSize]; 
PVector vectorSet [][] = new PVector [boardSize][boardSize];
int cellWidth; // Size of the fields
final int mikroplastikSize = 10;
final int VectorSize = 10;
int randomVectorPosition;
float mikroplastikSpeed = 1.;

void setup() {
  // basic Setup
  size(700, 700);
  smooth();
  rectMode(CORNER);
  ellipseMode(CENTER);
  cellWidth = width/boardSize; // width of the cell dependens on the size of the board 
  mikroplastikParticles = new ArrayList();

  // visualization of the board (understanding purpose only)
  fill(255, 255, 255);
  stroke(0);
  for (int r = 0; r&lt;boardSize; r++) {
    for (int c = 0; c&lt;boardSize; c++) {  
      rect(r * cellWidth, c * cellWidth, cellWidth, cellWidth);
    }
  }

  // now we start to initialize the particles
  for (int r = 0; r&lt;boardSize; r++) // we want to fill every single field
    for (int c = 0; c&lt;boardSize; c++) 
      for (int anz = 0; anz &lt; numOfMikroplastikPerField; anz++) // we can choose how many particles per field we want with "numOfMikroplastikPerField"
        mikroplastikParticles.add(new Mikroplastik(r*cellWidth+random(cellWidth), c*cellWidth+ random(cellWidth))); // mikroplastik per field gets added

  // setting up the vectors
  for (int x = 0; x&lt;boardSize; x++) {
    for (int y = 0; y&lt;boardSize; y++) {
      randomVectorPosition = (int)random(2);
      if (randomVectorPosition == 0)
      vectorSet[x][y] = new PVector(0, random(cellWidth));
      else
      vectorSet[x][y] = new PVector(random(cellWidth), 0);
    }
  }
}

void draw() {
  background(255);
  for (int i=0; i &lt; boardSize*boardSize*numOfMikroplastikPerField; i++) { 
    Mikroplastik myMikroplastik = (Mikroplastik)mikroplastikParticles.get(i); // getting all vectors from the array
    myMikroplastik.display(); // assigning a "to do" for the vectors
  }
}

class Mikroplastik  { // the actual mikroplastik class

  PVector mikroplastik = new PVector(0, 0); // the mikroplastik is a vector object
  PVector sum = new PVector(0, 0);

  Mikroplastik(float tempX, float tempY) {
    mikroplastik.set(tempX, tempY);
  }

  void display() 
{ // how the mikroplastik looks like 
    fill(#FF0000);
    noStroke();
    ellipse(mikroplastik.x, mikroplastik.y, mikroplastikSize, mikroplastikSize);

    // PVector mouse = Vector.vector(tempX, tempY);
    PVector mouse = new PVector(mouseX, mouseY);
    mouse.sub(mikroplastik);
    mouse.mult(0.05);
    sum.add(mouse);
    sum.normalize();
    sum.mult(mikroplastikSpeed);
    mikroplastik.add(sum);

  }
}
</code></pre>
]]></description>
   </item>
   </channel>
</rss>