Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - Flipping an image in p5.js using scale

I'm creating a program where it has animations walking in place to the left or to the right depending on whether I press the left or right arrow. The program works fine when I press the right arrow since the images were initially facing to the right, but when I try to flip the images using scale to have it walk in the opposite direction they disappear completely.

var Guy;
var Green;
var Robot;
let imgnum = 0;
let time = 0;


function preload() {
  Guy = loadImage("SpelunkyGuy.png")
  Green = loadImage("Green.png")
  Robot = loadImage("Robot.png")
  GuyStand = Guy.get(0,0,80,80)
}
function setup() {
  createCanvas(400, 400);
  x = int(random(0,5));
  y = int(random(0,5));
  x2 = int(random(0,5));
  y2 = int(random(0,5));
  x3 = int(random(0,5));
  y3 = int(random(0,5));
}

function draw() {
  background(220);
  if(keyCode === RIGHT_ARROW){
    image(Guy,x*80,y*80,80,80,imgnum*80,0,80,80);
    image(Green,x2*80,y2*80,80,80,imgnum*80,0,80,80);
    image(Robot,x3*80,y3*80,80,80,imgnum*80,0,80,80);
    if (time > 10){
      imgnum += 1;
      if(imgnum >= 9){
        imgnum = 0;
      }
      time = 0;
    }
    time++;
  }
  
  if(keyCode === LEFT_ARROW){
    scale(-1.0,1.0);
    image(Guy,x*80,y*80,80,80,imgnum*80,0,80,80);
    image(Green,x2*80,y2*80,80,80,imgnum*80,0,80,80);
    image(Robot,x3*80,y3*80,80,80,imgnum*80,0,80,80);
    if (time > 10){
      imgnum += 1;
      if(imgnum >= 9){
        imgnum = 0;
      }
      time = 0;
    }
    time++;
  }
  

}
question from:https://stackoverflow.com/questions/66056987/flipping-an-image-in-p5-js-using-scale

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not seeing a negative scale documented in the p5.js scale reference page.

An alternative solution would be to have right and left facing images, then switch out the image depending on direction faced.

Example:

let lefty, righty;

function preload(){
  lefty = loadImage('left-facing.jpg');
  right = loadImage('right-facing.jpg')
}

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

function draw() {
  background(220);

  if(keyCode === LEFT_ARROW){
    image(lefty,0,0,width,height)
  }
  if(keyCode === RIGHT_ARROW){
    image(righty,0,0,width,height)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...