我创建了一个产生球的程序,可以通过单击并拖动鼠标来抛出。我决定添加一个功能,可以通过单击按钮添加墙。然后墙壁将移动到鼠标的位置。
void setup() {
size(640,360);
background(50);
}
// Speed of ball
float xSpeed = 5;
float ySpeed = 1;
// Ball size
float circleRad = 12;
// Ball position
float circleX = 0 + circleRad;
float circleY = 180;
// Ball physics
float gravity = 0.35;
float friction = 0.075;
// Wall position
float wallX = 320;
float wallY = 180;
// Wall dimensions
float wallWidth = 20;
float wallHeight = height;
// Determines whether or not the wall's position is currently being changed
boolean wall = false;
void draw() {
background(50);
noStroke();
fill(85);
rect(25,25,50,50);
ellipseMode(RADIUS);
rectMode(CENTER);
// If button is pressed, wall is being created/moved
if(mousePressed && mouseX <= 50 && mouseY <= 50) {
wall = true;
}
// If mouse is pressed and wall isnt being created/moved, move circle to mouse's position
if (mousePressed && wall == false) {
circleX = mouseX;
circleY = mouseY;
}
// Creates/moves wall
if(wall == true){
wallX = mouseX;
fill(170);
rect(wallX, wallY, wallWidth, wallHeight);
}
// Creates ball
fill(255);
ellipse(circleX,circleY,circleRad,circleRad);
// Bounces ball off of walls/ceiling/floor, implements ball physics
if (!mousePressed){
circleX+=xSpeed;
circleY+=ySpeed;
if(circleX >= width - circleRad) {
xSpeed *= -1;
circleX = width - circleRad;
}
if (circleX <= 0 + circleRad) {
xSpeed *= -1;
circleX = 0 + circleRad;
}
if (circleY >= height - circleRad) {
ySpeed *= -1;
ySpeed += 0.9;
circleY = height - circleRad;
}
if (circleY <= 0 + circleRad) {
ySpeed *= -1;
circleY = 0 + circleRad;
}
if((circleY <= 0 + circleRad || circleY >= height - circleRad) && xSpeed >= 0) {
xSpeed -= friction;
}
if((circleY <= 0 + circleRad || circleY >= height - circleRad) && xSpeed <= 0){
xSpeed -= friction * -1;
}
if(xSpeed >= -0.1 && xSpeed <= 0.1) {
xSpeed = 0;
}
if(xSpeed <= 0){
xSpeed -= friction * -0.1;
}
if(xSpeed >= 0){
xSpeed -= friction * 0.1;
}
ySpeed += gravity;
}
}
// Sets ball speed to speed of mouse once mouse is released, allowing for throwing of ball
void mouseReleased(){
xSpeed = mouseX - pmouseX;
ySpeed = mouseY - pmouseY;
}
我还没有完成这个功能,(球还没有从墙上反弹,也没有办法阻止墙跟着鼠标)但我遇到了一个问题。每当我点击按钮创建墙壁时,程序就会看到我已经释放了鼠标,并决定扔球。通常有人在点击时不会移动鼠标,因此结果是球的速度设置为0.我试图通过在mouse语句中包含mouseReleased()函数内部的代码来解决这个问题: / p>
void mouseReleased(){
if(wall == false){
xSpeed = mouseX - pmouseX;
ySpeed = mouseY - pmouseY;
}
}
但这会导致另一个问题;当按下鼠标时,球在空中暂停,并在释放鼠标时恢复。我怎样才能按下按钮,墙壁开始建造,球完全不受影响?
答案 0 :(得分:0)
你拥有在if
声明中移动球的所有逻辑:
if (!mousePressed){
因此,只有在未按下鼠标时,您的球才会移动。换句话说,当您按下鼠标时,球会停止移动。
快速而愚蠢的解决方法是为此if
语句添加一些逻辑。想想你何时想要移动球:当没有按下鼠标,或者按下鼠标但是你正在移动墙壁时,对吗?这看起来像这样:
if (!mousePressed || wall){
但更一般地说,您可能想退一步并清理一下代码。查看您在mousePressed
语句中检查wall
和if
的次数。您可能应该尝试重构,以便您的逻辑更容易阅读。这将有助于您思考代码正在做什么,这将使您的生活更轻松。