[英]Ball not coming back after colliding in p5.js
var x, y, speed, speed2, speedx, speedy;
function setup() {
createCanvas(1200, 630);
x = 50;
y = 300;
speed = 20;
speed2 = 20;
speedx = createSlider(2, 50, 20);
speedx.position(1000, 100);
speedx.style('width', '200px');
speedy = createSlider(10, 50, 20);
speedy.position(1000, 150);
speedy.style('width', '200px');
}
function draw() {
background("white");
x = x + speedx.value();
y = y + speedy.value();
if (x > 1170) {
x = x - speedx.value();
}
if (x < 10) {
x = x + speedx.value();
}
if (y > 610) {
y = y - speedy.value();
}
if (y < 15) {
x = x + speedx.value();
}
let color1 = color("black");
fill(color1);
ellipse(x, y, 20);
}
** 我是 p5.js 的新手並做了這個(我的第一個代碼),但它沒有按我預期的那樣工作
請通過回答此代碼來幫助我**
目前,您的代碼不會讓球“回來”,因為雖然它限制了 x 和 y 位置,但它不會改變 x 和 y 速度(所以一旦球到達邊緣,它只會堅持在那里)。 您在邊緣限制邏輯方面也有一些缺陷。
var x, y, speedx, speedy; function setup() { // make the canvas cover the window createCanvas(windowWidth, windowHeight); x = width / 2; y = height / 2; // create slider ranges such that things don't always go down and to the right speedx = createSlider(-10, 10, 2); speedx.position(10, 10); speedx.style("width", "200px"); speedy = createSlider(-10, 10, 2); speedy.position(10, 50); speedy.style("width", "200px"); } function draw() { background("white"); x = x + speedx.value(); y = y + speedy.value(); if (x > width - 10) { x = x - speedx.value(); } if (x < 10) { // presumably the reason we're going off the screen is that speedx is negative. x = x - speedx.value(); } if (y > height - 10) { y = y - speedy.value(); } if (y < 10) { y = y - speedy.value(); } let color1 = color("black"); fill(color1); ellipse(x, y, 20); }
html, body {margin:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
你可以這樣做(訪問 codecademy 了解詳情: https://www.codecademy.com/courses/learn-p5js/lessons/p5js-animation )
speedx *= -1
你可以用speedy
做同樣的事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.