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;
最佳答案
如果您已经或知道如何计算 x 轴和球杆之间的角度(我假设这是台球),那么要使球朝那个方向移动,如果我正确理解您的代码,您可以只需根据所击球的 dx 和 dy 设置即可
dx = power*cos(angle)
dy = power*sin(angle)
您可能必须采用负角度,具体取决于坐标系(如果在 y 方向上向上是正值还是负值),以及您计算的精确角度。最简单的可能就是将其插入,看看会发生什么!
编辑:
与您的问题无关,但作为一种风格问题,将移动和绘制球的逻辑移至 Ball 类可能是个好主意。这样,每次勾选时,您都可以通过为 Ball 类的每个实例调用适当的 draw()
方法在屏幕上绘制球。那么一次移动多个球就会容易得多。
编辑2: 我刚刚意识到,如果您知道单击的点,那么您实际上可以在没有三角学的情况下解决问题。假设 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 的相对长度,为了获得正确的幂,我们只需要标准化并乘以幂即可。
关于java - 如何让小球根据点击的位置朝特定方向移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877914/