简体   繁体   中英

Creating a sketch to place random images at mouse positions in p5.js

So I am currently working on a sketch for p5.js that places two random images at a location the user clicks on in the canvas. The idea is to create a "paper doll" of a character with a randomized head and a randomized body at any location where the user chooses to click. The random images in question are the image for the head and the image for the body. I decided to name the images with numbers so that I could use string interpolation to randomize the images with the numbers in the name of the images.

I have already managed to successfully display the paper doll without randomization of the images, but I now can't seem to successfully randomize the two different images upon mouse click. How can I randomize the images displayed using this type of string interpolation technique?

 let body = []; let head = []; let characters = []; function preload() { for (let i = 0; i <= 2; i++) { body[i] = loadImage('Body_' + i + '.png') console.log(print(body[i])); } for (let i = 0; i <= 2; i++) { head[i] = loadImage('Head_' + i + '.png') console.log(print(head[i])); } } function setup() { createCanvas(1000, 1000); } function mousePressed() { let R = random(0, 1); let c = new pcCharacter(R, mouseX - 150, mouseY - 300) characters.push(c); } function draw() { background(0); for (let i = 0; i < characters.length; i++) { characters[i].characterDraw(); } } // a class for the paperdoll class pcCharacter { constructor(r, x, y) { this.r = r; this.x = x; this.y = y; } characterDraw() { image(body[this.r], this.x, this.y + 130) image(head[this.r], this.x + 60, this.y) } }

try to make two new variables (say a and b)

assign them random values between 0 and 3

floor the variables

load only the body[a] and face[b]

make the doll using only these images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM