How to make a real time type writer with p5.js

I am currently working on a school project that I would like to design a typewriter that goes wrong, which means that the text output is different from the text input by the user. Here is my code and I am not quite sure how to make the text goes to the next line and to rotate the text horizontally(maybe flip the canvas horizontally).

I am quite new to programming and p5.js, really appreciated if anyone can help.

var contents = "";
var r,g,b;
var x,y;
var bell
var ding
var a,b

function setup() {
  createCanvas(600,400);
  r = random(255);
  g = random(255);
  b = random(255);
  x = 50;
  y = 50;

  soundFormats('wav');
  bell = loadSound('typing.wav');
  ding = loadSound('return.wav')
}

function draw() {
  background(200);
  fill(r,g,b);
  textSize(50);
  text(contents, x, y, 400, 600);

    if(textWidth>400){
    y = 100;
  }

//   x = x + random(-1, 1);
//   y = y - 1;

//   Reset to the bottom
//   if (y < 0) {
//   y = height;
// }
}

function myBox(k) {
 var txt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 var i = txt.indexOf(k);
 var next;

  if (i+1 < txt.length) {
   next = txt[i+1];
 }
  else {
  next = txt[0];
 }
  return next;
}

function keyTyped() {
  contents += myBox(key);
  r = random(255);
  g = random(255);
  b = random(255);
  bell.play();
}

function keyPressed() {
  if (keyCode === ENTER) {
    ding.play();
  }
}
Tagged:

Answers

  • It's hard to help with general "how do I do this" type questions. You'll have much better luck if you ask a specific "I tried X, expected Y, but got Z instead" type questions. The best advice I can give you is to break your problem down into smaller steps and take those steps on one at a time.

    For example, you aren't asking about playing sounds, right? That means you can completely get rid of the code that's used for playing sounds. Start over with a blank sketch and create a MCVE that demonstrates one problem at a time.

    You say one of your problems is that you want to flip text horizontally. Can you create a small example sketch that just shows a single hard-coded line of text flipped horizontally? Get that working perfectly before trying to integrate it into your final project.

    Good luck.

  • If you stored the typed characters as a matrix and split them up by the enter key you should be able to manipulate the lines separately.

    Play around with https://p5js.org/reference/#/p5/rotate for how to rotate in 2D space.

Sign In or Register to comment.