有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于新位置的java随机双生成器

我有一个代码,当输入参数时,它会向我的鼠标光标复制引力。单击鼠标时,会创建一个反向效果,将对象(矩形)推离鼠标。我试图将其设置为,当你点击并按住时,当对象在x或y坐标中击中某个数字时,它将随机改变该对象的x和y。这是我的密码。注释区域是我试图使x和y在达到500个参数时变得随机的地方

import java.awt.*;

import java.util.Random;
    public class Ball
{

private Color col;
private double x, y;         // location
private double vx, vy;       // velocity

public Ball(int new_x, int new_y, int new_vx, int new_vy)
{
     x = new_x; 
     y = new_y; 
     vx = new_vx; 
     vy = new_vy;
}

public Ball()
{
    Random gen = new Random();
    x = gen.nextInt(480);
    y = gen.nextInt(480);
    vx = gen.nextInt(10);
    vy = gen.nextInt(10);

    col = new Color(gen.nextInt(255),gen.nextInt(255),gen.nextInt(255));

}

void paint( Graphics h)
{
    h.setColor(col);
    h.fillRect((int)x,(int)y,20,20);  
}

void move(int currentX, int currentY, boolean isButtonPressed )
{
    double dvx, dvy, rx, ry;
    double r_mag;


    x = x + vx;
    y = y + vy;  

    //bounce
    if  (x > 480 || x < 0)
       vx = -vx;
    if (y > 480 || y < 0)
        vy = -vy;



   if ( currentX <500 && currentY <500)   // mouse is on canvas, apply "gravity" 
   {
      rx = currentX - x;
      ry = currentY - y;
      r_mag = Math.sqrt((rx*rx) + (ry*ry));

//           if ( x = 500 || y = 500)
//             Random x = new Random();
//             x.nextDouble();
//             Random y = new Random();
//             y.nextDouble();

      if (r_mag < 1)
        r_mag = 1;

      dvx = (rx / r_mag);
      dvy = (ry / r_mag);

      if (isButtonPressed)
      {
        vx = vx - dvx;   // + makes balls move to cursor.
        vy = vy - dvy;   // - makes balls move away from cursor. 
      }
      else 
      {
        vx = vx + dvx;   // + makes balls move to cursor.
        vy = vy + dvy;   // - makes balls move away from cursor.

      }
    }

    // reduce speed slowly
    vx = .99*vx;
    vy = .99*vy;
}

}

共 (1) 个答案

  1. # 1 楼答案

    The commented area is where I tried to make x and y go random when it hits 500 parameters.

    所以当xy达到500时,您想随机重新定位对象吗

    而不是

    //           if ( x = 500 || y = 500)
    

    这是作业,不是比较

    //             Random x = new Random();
    

    重新声明x,不是你想要的

    //             x.nextDouble();
    

    无效声明

    //             Random y = new Random();
    //             y.nextDouble();
    

    见上文

    您可以使用Math.random(),如中所示

    if (x == 500 || y == 500) {
        x = Math.random()*480;
        y = Math.random()*480;
    }
    

    (注意:Math.random()返回半开区间[0,1)中的double,因此必须对其进行缩放;我使用的480的缩放因子是一个猜测),或者(不太好,我认为)每次输入if时都创建一个新的Random实例

    但是,

    1. xy和速度vxvydoubles,因此运动不太可能让xy精确地变成500,因此您可能应该在这种情况下测试>=,而不是==

    2. 在代码中,当任一坐标通过480时,翻转速度,因此很难达到500或更远,并且只能通过使用鼠标进行明智的加速来实现,因此可能需要更小的阈值