What is the best way to show 1000 objects moving in a field?

Hello. I'm trying to JavaFX 2.0 and higher. I want to create 1000 objects (because now they can be rectangles) and move them randomly (for now). What is the best way to do this? Do I have to create an initial keyframe for each object? I was watching the demo of BrickBreaker. Is all that I need? I'm looking for a simple example. For example: ColorfulCirclesSample. Basically, what I want to do is create 1000 rectangles with random attributes including a vector (direction and speed) and show them using JavaFX 2.x.

Thanks in advance.

ServandoC

Not that this is the best way, but it's an example, you can try:

import java.util.Random;
import javafx.animation.*;
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.util.Duration;

// animates a 1000 objects (klingons) moving around the scene at random directions and velocity.
public class ObjectsInMotion extends Application {
  private static Random random = new Random(42);
  private static final int    N_OBJECTS   = 1000;
  private static final int    OBJECT_SIZE = 20;
  private static final Image  KLINGON = new Image("http://icons.mysitemyway.com/wp-content/gallery/green-jelly-icons-transport-travel/038998-green-jelly-icon-transport-travel-star-trek-sc43.png", OBJECT_SIZE, OBJECT_SIZE, true, true);
  public static void main(String[] args) { launch(args); }
  @Override public void start(final Stage stage) throws Exception {
    // initialize the stage to fill the screen with klingons.
    stage.setTitle("Starboard bow");
    stage.setFullScreen(true);
    final double screenWidth    = Screen.getPrimary().getBounds().getWidth();
    final double screenHeight   = Screen.getPrimary().getBounds().getHeight();
    final Group objects = new Group(constructObjects(N_OBJECTS, OBJECT_SIZE, (int) screenWidth, (int) screenHeight));
    stage.setScene(new Scene(objects, screenWidth, screenHeight, Color.MIDNIGHTBLUE.darker().darker().darker()));
    stage.show();

    // press any key to exit the program.
    stage.getScene().setOnKeyTyped(new EventHandler() {
      @Override public void handle(KeyEvent event) {
        stage.close();
      }
    });

    // move the klingons around according to their motion vectors.
    final Timeline timeline = new Timeline(
      new KeyFrame(
        new Duration(1000/30), // update the klingon's motion 30 times a second.
        new EventHandler() {
          @Override public void handle(ActionEvent event) {
            for (Node n: objects.getChildren()) {
              // apply the motion vector for this object to determine the object's new location.
              MotionVector vector = (MotionVector) n.getUserData();
              double tx = n.getTranslateX() + vector.velocity * Math.cos(Math.toRadians(vector.angle));
              double ty = n.getTranslateY() + vector.velocity * Math.sin(Math.toRadians(vector.angle));

              // wrap the objects around when they fall off the starfield.
              if (tx + n.getLayoutX() > screenWidth)  tx -= screenWidth;
              if (tx + n.getLayoutX() < 0)            tx += screenWidth;
              if (ty + n.getLayoutY() > screenHeight) ty -= screenHeight;
              if (ty + n.getLayoutY() < 0)            ty += screenHeight;

              // update the object co-ordinates.
              n.setTranslateX(tx);
              n.setTranslateY(ty);
            }
          }
        }
      )
    );
    timeline.setRate(5);
    timeline.getCurrentRate();
    timeline.setCycleCount(Animation.INDEFINITE);
    timeline.play();
  }

  // construct an array of n objects of rectangular size spaced randomly within a field of width and height.
  private Node[] constructObjects(final int n, final int size, final int width, final int height) {
    Node[] nodes = new Node[n];
    for (int i = 0; i < n; i++) {
      ImageView node = new ImageView(KLINGON);
      node.setLayoutX(random.nextInt(width  - size / 2));
      node.setLayoutY(random.nextInt(height - size / 2));
      MotionVector vector = new MotionVector();
      node.setUserData(vector);
      // rotate the klingon to align with the motion vector accounting for the klingon image initially pointing south-west.
      node.getTransforms().add(new Rotate(vector.angle + 225, node.getFitWidth() / 2, node.getFitHeight() / 2));
      nodes[i] = node;
    }

    return nodes;
  }

  // polar co-ordinates of a motion vector.
  class MotionVector {
    final double velocity = random.nextDouble();
    final double angle    = random.nextDouble() * 360;
  }
}

Tags: Java

Similar Questions

  • What is the best way to show/hide n number of columns?

    Hello

    I have a dynamic report that I have show/hide columns works using the code below. But when there is 500 or more lines, that it takes about a minute or more just waiting to see the columns that toggle.

    What is the best way to do it?

    Existing JavaScript
    [script language = "JavaScript" type = "text/javascript"]
    var mymonths.length = maxcnt;
    function hideMaxEarn() {}
    for (var j = 0; j [maxcnt; j ++) {}
    hideColumn('MON'+mymonths[j],'MAXCOL'+mymonths[j]);
    hideColumn('MON'+mymonths[j],'EARNCOL'+mymonths[j]);
    }
    hideColumn ('MON13', 'MAXCOL13');
    hideColumn ('MON13', 'EARNCOL13');
    }
    function showMaxEarn() {}
    for (var j = 0; j [maxcnt; j ++) {}
    showColumn('MON'+mymonths[j],'MAXCOL'+mymonths[j]);
    showColumn('MON'+mymonths[j],'EARNCOL'+mymonths[j]);
    }
    showColumn ('MON13', 'MAXCOL13');
    showColumn ('MON13', 'EARNCOL13');
    }
    function getCellIndex (pRow, pCell) {}
    for (var i = 0, n = pRow.cells.length; i [n; i ++) {}
    If (pRow.cells [i] == pCell) return i;
    }
    }
    function hideColumn (pMon, pCol) {}
    var l_Cell = $x (pCol);
    var l_Table = html_CascadeUpTill (l_Cell, 'TABLE');
    var l_Rows = l_Table.rows;
    l_CellI = getCellIndex (l_Cell.parentNode, l_Cell);
    for (var i = 0, n = l_Rows.length; i [n; i ++) {}
    If (I! = 0) {}
    html_HideElement (l_Rows [i]. Cells [l_CellI]);
    } else {}
    $x (pMon) .colSpan $x (pMon) .colSpan = - 1;
    }
    }
    }
    function showColumn (pMon, pCol) {}
    var l_Cell = $x (pCol);
    var l_Table = html_CascadeUpTill (l_Cell, 'TABLE');
    var l_Rows = l_Table.rows;
    l_CellI = getCellIndex (l_Cell.parentNode, l_Cell);

    for (var i = 0, n = l_Rows.length; i [n; i ++) {}
    If (I! = 0) {}
    html_ShowElement (l_Rows [i]. Cells [l_CellI]);
    } else {}
    $x (pMon) .colSpan = 3;
    }
    }
    }
    return;
    }
    [script]

    Hi Bill,

    Can you just check to see if the report actually adds the ID attribute for each TD. In a normal report, if you include the ENAME field, for example, all TD in this column have an ID = "ENAME". If this is the case, you can use document.getElementByID ("ENAME") to retrieve a collection of these - this would be faster browse this collection through the rows/cells.

    In addition, if possible, you should only perform research and calculations once. You have mymonths [j] several times in loops - create a variable to hold this for each iteration of the loop and refer to the variable. You also n = l_Rows.length in loop definition - put this above the loop that you only need to calculate this time.

    You can also find more efficient to perform ObjectName. style.display = 'none' * instead of the html_HideElement() method as it is easier.

    If FF3 was a bug in which does not hide the NECK tag columns, I suggest using those rather--it would mean the creation of a new report template, but it would have been the quickest method as you can style an entire column to style her NECK tag (drawback, it's that the NECK tag cannot be created dynamically so it should appear in the report model).

    Andy

    Published by: ATD 26 Sep, 2008 15:03

  • What is the best way to show out sold on site?

    I have a site selling paintings online and wish to paintings sold but tag always leave them in the store (that people can see the material and the general style). I initially set it up as a custom field, but concluded that a user could add another article to your shopping cart. Nobody knows what the best approach is to obtain products ideally show the sold sign when they are purchased and also have the opportunity for the artist to label the sold product if it sold by other means. ?

    Thank you


    Deb

    Hi Deb, type in "Out of stock" in the great hunting area and load results to wait. A just below yours in the results for example
    Always try to do a search first

  • I want to show a hand wiping snow off the screen. What is the best way to do it?

    I want to show a hand wiping snow off the screen. What is the best way to do it?

    You might try shooting through the snow on a green plastic non-brillant/Matt surface, have a camera on a tripod to research on snow and wipe the snow with your hand, pushing as well, otherwise all of the snow, so you find yourself alone with the Green surface. Then, go through the many Keylight tutorials out there to key on the Green and just the snow and the hand.

  • INTERFACE design - what is the best way to allow the user to define a kind of infusion at various times (non-periodic)?

    I want to allow the user to specify a curve like this:

    Such as some under - VI shows the A2 value when a variable of time is between R1, A1 when the time variable is between A2 and A3 when time is in the range A3.

    My design looks like this:

    With the error checking that looks like this:

    My question is, is the approach of the table according to optimal? Otherwise, how could combat this?

    I think I can summarize the conversation on this point as a response to the original question (what is the best way...) -to start writing code, to think about what you want to accomplish and write it down (otherwise known as 'Write the first Documentation').  One of the points of a good User Interface is that it is not allow users to "stupid mistakes" - it leads the user "by hand", limiting the entries to the "legal values" and demanding that the entries be made logically.

    If you were going to have a list of Infusions to enter, it is therefore logical to decide or not to enter into time intervals (which are always > 0) or order the times (which, logically) are still growing.  You can (and should) decide that you (or you may have a control that allows the user decide, but maybe it's too flexible) and then apply your "rules".

    Let's say you've decided on "Intervals" (which seems to me to be more User Friendly).  After the user has entered the intervals (and you've provided a nice plot of perfusion vs. time), pouvez allow you the user to an interval of 'split', 'Delete' an interval, or "Edit the Infusion" interval, or you can decide to have a choice more simple "accept or start again" - If you have only a few intervals, the last would be the simplest (and therefore best) design choice.

    Spend more time thinking before coding usually pays Big dividends!

    (Speaking of sad experience) Bob Schor

  • What is the best way to save an array of objects and then load it?

    Hi, what is the best way to save and load an array of objects?

    I hade a code like that, but it does not work:

    var test = new Array();
    test.push(new Foo("a"));
    for (var i = 0; i < test.length; i++) {
        console.log(test[i]);
    }
    // save and load, then show again
    localStorage.setItem("test", test);
    var test2 = localStorage("test");
    for (var i = 0; i < test2.length; i++) {
        console.log(test2[i]);
    }
    

    the problem is, the first newspaper that get the things I want. The second time I get:

    Uncaught TypeError: Property 'localStorage' of object [object Object] is not a function
    

    The work around this problem is to stringify before saving and then analyze before loading.

    http://StackOverflow.com/a/2010948/773263

    Although I said, it is better to use IndexDB.

  • What is the best way to make the completely white background for the pictures of the products?

    What is the best way to make the completely white background for the pictures of the products?  I just need to show a product on a completely white background.

    Shoot on properly informed white background is easy. Then be tot apply an adjustment layer to whiten the BG, then apply a mask for the domains you want to not so bright.

  • What is the best way to migrate PSE6 catalogue (Wxp) to new computer W7, PSE11?

    What is the best way to migrate PSE6 catalogue (Wxp) to new computer W7, PSE11?  Recovery of previous PSE6 (Wxp) after a HD failure gave rise to images showing, but not not opening due to connection problems.  Had to restore backup images and rebuild the catalog and albums.  Found a fix to third later that has no support spent PSE8.  Try to make this migration to painless PSE11.

    William47 wrote:

    What is the best way to migrate PSE6 catalogue (Wxp) to new computer W7, PSE11?  Recovery of previous PSE6 (Wxp) after a HD failure gave rise to images showing, but not not opening due to connection problems.  Had to restore backup images and rebuild the catalog and albums.  Found a fix to third later that has no support spent PSE8.  Try to make this migration to painless PSE11.

    This is a very common and classic situation:

    http://helpx.Adobe.com/Photoshop-elements/KB/backup-restore-move-catalog-Photoshop.html

    Just make sure that your backup on the external drive is ok: you should find a "backup.tly" file in the folder.

    Use the organizer of PSE11 to restore the backup of the PSE7: the first step restores all your multimedia files, the second automatically performs a conversion of catalogue in format PSE11.

    Read the note in the link above on the restoration of XP to the ulterior Win operating system. You can also restore to a location 'custom '. For example in a "C:\My new library" folder. Make sure the main folder is accessible to all users, and if you wish, you can move the catalog (database), itself from this location to the default location: Catalog Manager, ability to move catalogs in location that is accessible to all users.

  • What is the best way to view an interactive report with 20 columns

    Hello

    I have an interactive report, given the number of columns (about 20).
    What is the best way to view this report... by default to scroll horizontally to see all the columns.
    I want to avoid horizontal scrolling.

    Thank you
    Deepak

    Hello Deepak,

    You mean apart using a smaller font size or a larger screen?
    You can think to combine / wrapping columns (so more data in a column).
    Or hide some less important data and show only on request.

    Greetings,
    Roel
    http://roelhartman.blogspot.com/
    You can reward this response in marking it as useful or Correct ;-)

  • What is the best way to buy an iPhone Unlocked 7?

    Hi all

    I am currently using T-Mobile and want to get the new iPhone 7. Since there is no option for a sim-free iPhone, what is the best way to buy the new iPhone? Should I get the T-Mobile one full fare? I know that he will be released version but it will come with a T-Mobile sim so what will do with the sim card? Put it away or give it to T-Mobile? Or should I wait for the version without card sim to appear, which I don't think that will come out until November, and I don't want to wait that long.

    Thank you in advance.

    If you do not want to wait to pay full price for the model from T-Mobile.  You can do whatever you want with the SIM card.

  • I'll do a clean install on a blank hard drive upgrade but want to keep my Firefox settings - what is the best way to do this?

    I'll do an upgrade from Windows XP to Windows 7. I will be installing Windows 7 on a new empty hard drive. I want to keep my bookmarks Firefox and Ad Ons. What is the best way to do it. Thank you for your help.

    Hello

    The best thing for you to do is to make a backup of your Firefox profile. It is a folder that stores bookmarks and Add-ons that you can then add to the reinstalled Firefox on your new operating system.

    Learn you more about the Firefox profile folder, how to backup and restore, here.

    I hope this helps, but if not, please come back here and we can look at in another option for you.

  • What is the best way to consolidate e-mail messages in the e-mail program, before deleting?

    I have an iMac with a capacity to 1.11 - 679,49 GB available. With the software updated.

    Model name: I

    I have emails out of my different accounts in a "random" folder, but is not free up space. If I move an email in "Archives" and then it always remains in the e-mail account, apparently duplicate email in two places. "

    ERGO: the question is...

    What is the best way to consolidate e-mail messages in the e-mail program, before deleting?

    (I hope I've inserted which may be useful, but I'm not sure about that.)

    Thank you

    ilenefrombaltimore

    Archive messages or move them to some other local mailboxes or mailboxes on the server. Don't know what you are trying to do because it appears that you have 2/3 of your hard disk.

    Why do you think archiving emails in 2 places? Where are you trying to save space to?

  • What is the best way to sync contacts with a host of webdav?

    I use Thunderbird and Contacts Android as of client applications with an owncloud 8 hosted remotely. I have activated the application Contacts on Owncloud and now I want to sync the contacts between these systems. What is the best way to do it?

    I try to get sorted first Thunderbird. I tried Addressbooks Synchronizer, but currently, it gives me a message telling me that my credentials are wrong or is sitting silently, do nothing. I am aware that it is a file synchronization, the method of synchronization not saved, so it is not ideal, in any case.

    Is there a better, good timing, method I can use? I refuse to the thing that he is an unreasonable request or that no one asked before me, but I can't seem to find the answer.

    Thanks, Martin

    WebDAV my initial reaction was sogo connector.
    These guys recommend the same http://kb.mozillazine.org/Sharing_address_books

    Here http://www.sogo.nu/english/downloads/frontends.html

  • What is the best way to copy the 700 lots of e-mail files to a new computer?

    I'm moving my wife and an old (Thunderbird, Win XP) computer to a new computer (Thunderbird Win 7). It has about 700 local folders with thousands of emails in them. What is the best way to copy to the new computer?

    The easiest is just to copy the whole profile.

    Menu help > troubleshooting information

    Close Thunderbird

    In windows Explorer, select all and copy.
    just stick on a thumb or other portable media to read/write (not the CD or the DVD)

    on the new Machine to repeat the troubleshooting and close the steps to get the current profile folder

    This time all the portable media stick in the profile to replace what is there

    Open Thunderbird, your additions of e-mail contacts does it all

  • What is the best way to retrieve deleted mp3 files? I am running OSX Leopard 10.5.8 on a PowerPC G5 tower. I'll be very grateful for any help in this matter. Thanks to Chris

    Hello

    What is the best way to retrieve deleted mp3 files? I had a lapse of attention and I deleted a folder containing most of my music files. It is for the most part, the mp3 but there was regular audio files and some wav files in there also. I am running OSX Leopard 10.5.8 on a PowerPC G5 tower. I have another PPC machine to help the recovery, if I need, but at the moment, he is not appearing on my network (3 computers). I'm trying to change this soon. I'll be really grateful for any help in this matter.

    Thanks to Chris

    If you emptied the Recycle Bin after you move the folder to the trash, and you don't have a time Machine or another backup, then it is lost, sorry.

Maybe you are looking for

  • Several corporate email accounts

    Hello; I have 2 settings sync business accounts on my defy + - but cannot work out how to display both Currently I have to go into settings and set one or the other as a default value to see the emails Or Wait for an email to come and go from the not

  • Aspire 5100

    Cover of my acer Aspire 5100 will not open

  • Unknown songs

    There are a bunch of songs on my Sansa Fuze and I have no idea how they got there - for example, "it's Yours to Keep" of medlar from Japan, or "Alias & Ehren" by Lillian.  I can work on what they were previously charged, and I can remove them if I wa

  • What are the steps to install new disk for Compaq Presario Notebook 61-420US

    I bought a Western Digital Scorpio Blue 320 GB Sata Hard Drive to replace the original fried.  The drive is installed.  After turning on the laptop computer, the error message was "no boot device found". I turned off laptop and you press F2.  I am ru

  • Double fault of PlayStation Portable 8008103E on Z3

    Hello everyone. Recently, I found on PSM and since I own the Sony Dual Z3, kinda wanted to see how it works. After downloading and entering the soft, it gives me error n. 8008103E. I already spoke with the assistance of Sony PSN team and they said, I