我想将滑块值乘以负一,以使球返回而不离开画布。 (我使用的是p5js)
var x = 200;
var y = 200;
let speedcontrolx;
let speedcontroly;
let outputx;
let outputy;
function setup() {
createCanvas(400, 400);
speedcontrolx = createSlider(-10, 10, 0);
speedcontroly = createSlider(-10, 10, 0);
outofboundsx = false;
outofboundsy = false;
}
function draw() {
outputx = speedcontrolx.value();
outputy = speedcontroly.value();
background("#dddddd");
stroke(0);
strokeWeight(4);
noFill();
ellipse(x, y, 40);
x += outputx;
y += outputy;
if( x > width-24 || x < 0+24) {
outputx = outputx *-1
}
if(y > height-24 || y < 0+24) {
outputy = outputy *-1
}
}
球刚刚离开画布:C
试试这个代码:
let x = 200;
let y = 200;
let speedXSlider, speedYSlider;
let speedX, speedY;
function setup() {
createCanvas(400, 400);
// Use p5.js createSlider to create sliders
speedXSlider = createSlider(-10, 10, 0);
speedYSlider = createSlider(-10, 10, 0);
}
function draw() {
background("#dddddd");
// Get slider values
speedX = speedXSlider.value();
speedY = speedYSlider.value();
// Update ball position
x += speedX;
y += speedY;
// Check boundaries and invert direction if necessary
if (x > width - 20 || x < 20) {
speedX *= -1;
}
if (y > height - 20 || y < 20) {
speedY *= -1;
}
// Draw the ball
stroke(0);
strokeWeight(4);
noFill();
ellipse(x, y, 40);
}