PVector

A 3D vector struct for position, velocity, and acceleration — position, velocity, and acceleration in a particle system, steering, or plain 3D math for custom Vertex()/Normal() geometry. Z defaults to 0 via the 2-argument constructor, so 2D-only sketch code that only ever wrote new PVector(x, y) keeps working unchanged.

On this page · 3 entries
instance (mutates)static (pure)
Add / Sub / Mult / DivAdd / Sub / Mult / Div
Normalize / Limit(max) / SetMag(mag)Dist(a, b) / Dot(a, b)
Rotate(rad)† / Set(x, y, z=0)FromAngle(rad)†
Lerp(v, amt)Lerp(a, b, amt)
Cross(v)Cross(a, b)
Mag() / MagSq() / Heading()† / Copy() / Array()AngleBetween(a, b)

†Rotate()/FromAngle()/Heading() only make sense for a vector lying in the XY plane and ignore Z, matching Processing's own documented 2D-only behavior for these three. For a genuine 3D rotation, rotate the point with RotateX/Y/Z() instead.

Operators · Random2D · Random3D

  • Operators
  • Random2D()
  • Random3D()

a + b, a - b, v * 2, v / 2 and -v return a new vector and never change either side, so pos += vel; just works. PVector.Random2D() and PVector.Random3D() give a random direction of length 1, like Processing's random2D()/random3D().

PVector is a struct. Copies are independent: var p = list[i]; p.Add(v); changes the copy, so write it back with list[i] = p;. Fields of a class (particle.Pos.Add(v)) are changed in place.

Cross

  • Cross(PVector v) → PVector

The 3D cross product — perpendicular to both vectors, following the right-hand rule. Does not mutate this (unlike most other instance methods here), matching Processing's own cross(), which always returns a new PVector. For two vectors lying in the XY plane (Z = 0), the result points purely along Z — exactly what you want for a 2D face's "up" normal, as in the faceted-gem example under Custom 3D shapes.

Runnable example

A complete sketch using this section. Test in Dana opens it in the IDE, or paste it into a new tab and press Run.

C#
// PVector: position, velocity and acceleration with operators.
public class Mover : Sketch
{
    PVector pos, vel;

    public override void Setup()
    {
        Size(600, 400);
        pos = new PVector(300, 200);
        vel = new PVector(0, 0);
    }

    public override void Draw()
    {
        Background(25, 30, 40, 40);
        var mouse = new PVector(MouseX, MouseY);
        var acc = (mouse - pos).SetMag(0.4f);   // steer toward the mouse
        vel = (vel + acc).Limit(8);
        pos += vel;

        NoStroke(); Fill(255, 190, 90);
        Circle(pos.X, pos.Y, 24);
        Stroke(255, 120);
        Line(pos.X, pos.Y, pos.X + vel.X * 6, pos.Y + vel.Y * 6);
    }
}