Snippets: random direction, screen wrap

Randomized speed:

  //randomize angle
  float angle = radians(random(360));
 
  //same speed
  float speed = 300;
 
  //break down the speed vector into x and y components
  float vX = speed * cos(angle);
  float vY = speed * sin(angle);
 
  //set the velocity
  circle.setVelocity(vX, vY);

Wrapping around the screen

//if the circle's x coordinate is < 0 teleport it to width keeping the same x
  if(circle.getX() < 0)
    circle.setPosition(width, circle.getY());
 
  if(circle.getX() > width)
    circle.setPosition(0, circle.getY());
 
  //similar and inverted for y coordinate
  if(circle.getY() < 0)
    circle.setPosition(circle.getX(), height);
 
  if(circle.getY() > height)
    circle.setPosition(circle.getX(), 0);

Full example here:

import fisica.*;
 
FWorld world;
 
FCircle circle;
 
void setup() {
  //sketch size
  size(800, 600);
 
  //initialize the library
  Fisica.init(this);
 
  //create a new Fisica world
  world = new FWorld();
 
  //for this example we are disabling the grab
  world.setGrabbable(false);
 
  //no gravity
  world.setGravity(0, 0);
 
  //create a circle
  circle = new FCircle(20);
  //appearance
  circle.setNoStroke();
  circle.setFill(255);
  //no inertia
  circle.setDamping(0);
  //make it lighter
  circle.setDensity(0.1);
  //make it bouncier
  circle.setRestitution(1);
  //no rotation
  circle.setRotatable(false);
  //set its position in the center of the sketch to the left
  circle.setPosition(400, 300);
  world.add(circle);
 
 
}
 
 
void draw() {
  world.step();
  background(0);
  world.draw(); 
 
  //if the circle's x coordinate is < 0 teleport it to width keeping the same x
  if(circle.getX() < 0)
    circle.setPosition(width, circle.getY());
 
  if(circle.getX() > width)
    circle.setPosition(0, circle.getY());
 
  //similar and inverted for y coordinate
  if(circle.getY() < 0)
    circle.setPosition(circle.getX(), height);
 
  if(circle.getY() > height)
    circle.setPosition(circle.getX(), 0);
 
}
 
void mousePressed()
{
 
 
  //randomize angle
  float angle = radians(random(360));
 
  //constant speed
  float speed = 300;
 
  //break down the speed vector into x and y components
  float vX = speed * cos(angle);
  float vY = speed * sin(angle);
 
  //set the velocity
  circle.setVelocity(vX, vY);
}
Posted in

Post a comment