2016-12-01 30 views
0

我对处理非常新,需要一些帮助。我正在尝试构建一个简单的踢球比赛。简单的想法:当球击中黄色的酒吧,球反弹。为了让球保持“活力”,你必须让它反弹黄色的酒吧。我成功地找到了反弹球的代码(它现在反弹了窗口的底部),并且我还成功创建了一个可以随鼠标移动的栏。到目前为止我还没有能够创造的是球实际上反弹了吧台。在这里寻找索姆帮助!谢谢!!使对象在处理中由mouseY/mouseX移动的对象反弹

float ballX = 100; 
float ballY = 0; 
float h = 50; 
int x, y; 


//create a variable for speed 
float speedY = 2; 

void setup() { 
    size(400,400); 
    smooth(); 
    noStroke(); 

    // change the mode we draw circles so they are 
    // aligned in the top left 
    ellipseMode(CORNER); 

} 

void draw() { 
    //clear the background and set the fill colour 
    background(0); 
    fill(255); 



    //draw the circle in it's current position 
    ellipse(ballX, ballY, h,h); 

    //add a little gravity to the speed 
    speedY = speedY + 0.5; 

    //add speed to the ball's 
    ballY = ballY + speedY; 


    //bar 
    x = mouseX; 
    y = mouseY; 
    fill(255, 255, 0); 
rect(x, y, 50, 10); 

    if (ballY > height - h) { 
    // set the position to be on the floor 
    ballY = height - h; 
    // and make the y speed 90% of what it was, 
    // but in the opposite direction 
    speedY = speedY * -0.9; 

    //switch the direction 
    //speedY = speedY; 
    } 
    else if (ballY <= 0) { 
    // if the ball hits the top, 
    // make it bounce off 
    speedY = -speedY; 
    } 


} 

回答

0

我警告你对你在互联网上找到刚刚复制粘贴代码。你必须真正理解它在做什么,否则当你的代码变得更加复杂时,你会头痛不已。尝试重写自己的逻辑,这样你就明白弹跳如何工作。

要确定球是否与桨相交,我建议拿出一张纸和一支铅笔并画出一些例子。尝试弄清楚球和桨在相交时的位置和大小。

但基本上,你需要检查球是否“在”矩形的范围内。如果球位于桨叶左侧右侧,桨叶右侧左侧,桨叶顶部下方和桨叶底部上方,则情况属实。