如何根据点击的位置使球向特定方向移动?

时间:2016-11-29 23:52:31

标签: java processing

    Table t1= new Table(300, 300);
float power=0;
float dx=0;
float dy=0;


void setup()
{
  size(1000, 600);
  frameRate(10);
}

void draw()
{
  strokeWeight(1);
  stroke(0, 0, 0); 
  strokeWeight(10);
  stroke(255, 0, 0);
  fill(26, 218, 35);
  rect(0, 0, 1000, 600);
  noStroke();
  fill(0);
  ellipse(0, 0, 80, 80);
  ellipse(1000, 0, 80, 80);
  ellipse(0, 600, 80, 80);
  ellipse(1000, 600, 80, 80);
  strokeWeight(1);
  stroke(0, 0, 0);
  fill(255);
  ellipse(t1.cue_ball.center.x, t1.cue_ball.center.y, 20, 20);

  dx=friction(dx);
  dy=friction(dy);


  if (mousePressed)
  {
    power+=5;
  }
 if (t1.cue_ball.center.x+30>1000 || t1.cue_ball.center.x-30<0)
  {
    dx*=-1;

  }
  if (t1.cue_ball.center.y+30 >=600 || t1.cue_ball.center.y -30<=0)
  {
    dy*=-1;
  }
  t1.cue_ball.center.x +=dx;
  t1.cue_ball.center.y +=dy;

}


void mouseReleased()
{
  dx=power*2;
  dy=power*2;
}
float friction (float c)
{
  c*=0.9;
  return c;
}

    class Ball 
{
  float rad;
  Point center;
  Point contact_point;
  color col;

  Ball ( float a, float b)
  {
    center = new Point (a+=dx, b+=dy);
    //contact_point= new Point(
  }
} 

class Table
{
  Ball [] b_arr;    
  Stick st;
  Ball cue_ball;

  Table ( float a, float b )
  {

    cue_ball= new Ball( a, b);
  }
}

class Point
{
  float x;
  float y;

  Point(float a, float b)
  {
    x=a;
    y=b;
  }
}

class Stick
{
  Point start_p;
  Point end_p;
  color col;
  int length;
}

所以我们想要添加一些东西,以便在点击球时它会相应移动。例如,如果在左上角单击它,它将沿对角线向右移动。如果点击左下方,它将向右斜上方移动。另外,有没有办法将它与角度对应?因此,点击点和中心之间的角度越大,对角线越陡。

添加了代码行我不确定需要添加的位置:

t1.cue_ball.center.x+=dx;
t1.cue_ball.center.y+=dy;
dx=t1.cue_ball.center.x-mouseX;
dy=t1.cue_ball.center.y-mouseY;
float n= sqrt(pow(dx,2)+pow(dy,2));

DX * =功率/ N;   DY * =功率/ N;

1 个答案:

答案 0 :(得分:1)

如果你有或者知道如何计算x轴和球杆之间的角度(我假设这是台球),那么为了让球朝那个方向前进,如果我正确理解你的代码,你可以根据

设置你击球的dx和dy
dx = power*cos(angle)
dy = power*sin(angle)

您可能需要取负角度,具体取决于坐标系(如果在y方向上升为正或负),以及您计算的角度。最简单的可能就是插上电源,看看会发生什么!

编辑: 与您的问题无关,但作为一种风格问题,移动您的逻辑以将球移动到Ball类可能是个好主意。因此,每次勾选时,您都会通过为Ball类的每个实例调用适当的draw()方法在屏幕上绘制球。然后一次移动几个球会容易得多。

EDIT2: 我刚刚意识到,如果你知道点击的位置,你可以在没有三角函数的情况下解决问题。假设cx,cy是你点击的点,x,y是球的中心,那么你的球的dx和dy可以计算为:

dx = x-cx
dy = y-cy
n = sqrt(dx^2 + dy^2)

dx *= power/n
dy *= power/n

说明: 球的出口速度应与咔嗒相对于球的方向相同。所以我们已经拥有了dx和dy的相对长度,并且为了获得正确的功率,我们只需要对功率进行归一化和乘法。