我正在創建一個生成球的程序,並且可以通過單擊並拖動鼠標來拋出。我決定添加一個功能,通過單擊按鈕可以添加牆。然後牆將被移動到鼠標的位置。正在運行mouseReleased()只有在一定的條件下
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.我試圖通過在if語句中將代碼包裝在mouseReleased()函數內部來解決此問題:
void mouseReleased(){
if(wall == false){
xSpeed = mouseX - pmouseX;
ySpeed = mouseY - pmouseY;
}
}
但是這會導致另一個問題;當鼠標按下時,球停在空中,當鼠標鬆開時恢復。我怎樣才能做到這一點,以便可以按下按鈕,開始建造牆壁,而球完全不受影響?
你可以發佈[mcve]嗎? – anacron
我相信我發佈的大部分代碼對於找到解決方案都很重要,我發佈了查找解決方案所需的所有代碼,並且只要答覆的人有處理(這是其中一個標籤)。 – Freguin
@anacron這確實是一個完整的例子。請注意,這是[tag:processing]問題,[Processing!= Java](http://meta.stackoverflow.com/questions/321127/processing-java)。這就是說,這不是一個**最小的**例子。這裏有很多額外的代碼,這就是爲什麼你很難思考邏輯的一部分原因。你應該儘量將問題的範圍縮小到儘可能少,同時仍然可以運行。 –