簡體   English   中英

使用約束() p5 js

[英]Using constrain() p5 js

我正在嘗試阻止image(player, x, y)偏離道路並在leftWallrightWall處停下來進行一個小型 p5 js 項目。 無論我如何嘗試實施constrain(n, low, high)它都行不通。 所以我決定改用這個:

if (x < leftWall) { x = leftWall;}

有人能告訴我如何在這段代碼中正確使用約束嗎?

 const A_Key = 65; const D_Key = 68; const initialX = 350; const initialY = 550; let x = initialX; let y = initialY; let leftWall = 54; let rightWall = 516; function draw() { background(bg); image(player, x, y); if (keyIsDown(A_Key)) { x -= speed; if (x < leftWall) { x = leftWall; } } if (keyIsDown(D_Key)) { x += speed; if (x > rightWall) { x = rightWall; } } }

每次執行約束時都需要將x分配給另一個變量

const A_Key = 65;
const D_Key = 68;
const initialX = 350;
const initialY = 550;
let x = initialX;
let y = initialY;

let leftWall = 54;
let rightWall = 516;

let img; // Declare variable 'img'.
let speed = 10;

function setup() {
  createCanvas(2000, 720);
  img = loadImage('s.jpg'); // Load the image
}

function draw() {
  background(220);
  
  let xc = constrain(x, leftWall, rightWall);
  
  image(img, xc, y);
  
  // Draw the walls.
  stroke(150);
  line(leftWall, 0, leftWall,height);
  line(rightWall, 0, rightWall,height);

  
   if (keyIsDown(A_Key)) {
    x -= speed;
  }
  if (keyIsDown(D_Key)) {
    x += speed;
  }
}

這是供參考:

https://p5js.org/reference/#/p5/constrain

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM