How do I make it that my object (robot) moves in random directions across the screen each time I run the program?

Question: How do I make it that my object (robot) moves in random directions across the screen each time I run the program?

Code:

//head 
var x = 200;

//body
var e = 400;

//arms
var x1= 280;
var y1 = 120;

//legs
var x2 = 230;
var y2 = 160;

var speedx = 5;
var speedy = 5;

function setup() {
  createCanvas(500,400);
}

function draw() {
  background(179,0,27);
  rectMode( CENTER)
  
  fill(68,100,173)
  stroke(70,105,149)
  
  //head
  ellipse(x,100,50,50);
  
  noFill(0)
  fill(164,176,245)
  noStroke(0)
  stroke(125,70,0)
  
  //body 
  rect(x,200,100,100)
  
  if ( x > 200){
  noFill(0)
  fill(245,143,41)
  noStroke(0)
  stroke(245,143,41)
 }
  
  x = x + speedx
  
  
  //right arm
  rect(x1,210,40,120)
  
  if ( x1 > 200){
    noFill(0)
    fill (125,70,0)
    noStroke(0)
    stroke(164,176,245)
  }
  
  x1 = x1 + speedx
  
  // left arm 
  rect(y1,210,40,120)
  
  y1= y1 + speedx
  
    x2 = x2 + speedx
  
  noFill(0)
  fill(70,105,149)
  noStroke(0)
  stroke(68,100,173)
  
  //right leg 
  rect(x2,350,40,140)
  
  //left leg 
  rect(y2,350,40,140)
  
  y2 = y2 + speedx
    
}
1 Like

First of all use x and y precise.

The 2nd value of rect is an y value, not 350 (you need a variable y2 here)

The first value is x, don’t call it y2.

Use speedx and speedy to change the x and y position of ALL the variables in the robot (x1,x2,x3,x4… and y1,y2,y3 respectively)

When you have done this cleaning up, you have a foundation you can build on.

Now say in setup ()

speedx=random(0.9, 5);
speedy=random(0.9, 5);

2 Likes

Also, if you want a more “natural” movement you can either:

  1. store an angle and speed. Each X frames, angle=angle+(random number less than pi/2). speedx=speedsin(angle). speedy=speedcos(angle).

  2. a simpler version of above: store a matrix of four [x,y] pairs to store all directions, and, each (random) frames, turn either left or right ((direction=direction++)%4 or (direction=4+direction)%4 ).

  3. If you know how to deal with angles, simply rebound against borders.