Better way of collision detection?

right now I'm experiencing problems with using the same speed
in reverse for collision detection (such as +=5 being countered by
-= 5). While this works most of the time, if the velocity of the
moving object changes, or on occasion, is out of sync with the map,
the moving object gets stuck like glue to the "wall".
Is there some other method of stopping the velocity when
colliding, without freezing the object in place?

I changed the = manspeed to = manspeed +1 and now the avatar
is now "moonwalking"???
for (i=1;i<49;i++){
the_wall = this["brick_mc"+i];
if(Key.isDown(Key.LEFT) &&
avatar_mc.body_mc.hitTest(the_wall)){
avatar_mc._x += manspeed +1;
if(Key.isDown(Key.RIGHT) &&
avatar_mc.body_mc.hitTest(the_wall)){
avatar_mc._x -= manspeed +1;
if(Key.isDown(Key.DOWN) &&
avatar_mc.body_mc.hitTest(the_wall)){
avatar_mc._y -= manspeed +1;
if(Key.isDown(Key.UP) &&
avatar_mc.body_mc.hitTest(the_wall)){
avatar_mc._y += manspeed +1;
}

Similar Messages

  • Using ModelsUnderRay Collision detection

    Ok first things first. I know you guys who have been reading
    my other post is going to get confused after reading this post so
    let me make myself clear. First yes I was previously trying to
    Havok, but I could not get my car to work with it. So This is why I
    am now asking stuff about ModelsUnderRay collision detection.
    Second, I found this tutorial at
    http://www.fbe.unsw.edu.au/learning/director/,
    and all things seem to go pretty good with using the max File the
    tutorial uses. Meaning I have not tried this on my car as of yet.
    In addition, considering that things seem to work with the
    tutorial, I now came up with a new question. Basically, if I am
    correct, I think by using the code below, this is not going to work
    with my car when the car is going up a hill. I conclude this by
    knowing that the tutorial just uses a character, meaning it is not
    like a using something like a car that has a chassis and 4 wheels.
    So my question is this... How can I get the chassis to follow the
    angle of the hill if I am using a behaviour that looks something
    like this...
    on collisionDetect me
    -- create a list to store collision data created by
    modelsUnderRay
    -- cast ray to left
    collisionList =
    p3Dmember.modelsUnderRay(pCharacter.worldPosition, \
    -pCharacter.transform.yAxis,#detailed)
    -- if models picked up by ray, then activate checkForCollion
    -- handler and send the collisionList as a parameter
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    -- cast ray to right
    collisionList =
    p3Dmember.modelsUnderRay(pCharacter.worldPosition, \
    pCharacter.transform.yAxis,#detailed)
    -- if models picked up by ray, then check for collision
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    -- cast ray forward
    collisionList =
    p3Dmember.modelsUnderRay(pCharacter.worldPosition, \
    pCharacter.transform.xAxis,#detailed)
    -- if models picked up by ray, then check for collision
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    -- cast ray backward
    collisionList =
    p3Dmember.modelsUnderRay(pCharacter.worldPosition, \
    -pCharacter.transform.xAxis,#detailed)
    -- if models picked up by ray, then check for collision
    if (collisionList.count) then
    me.checkForCollision(collisionList[1])
    end
    on checkForCollision me, collisData
    -- grab the #distance value from the CollisionList
    dist = collisData.distance
    -- check if distance is less than width of bounding box
    if (dist < pCharBoundingBox.resource.width ) then
    -- get distance of penetration
    diff = pCharBoundingBox.resource.width - dist
    -- calculate vector perpendicular to the wall's surface to
    move the character
    -- using the #isectNormal property
    tVector = collisData.isectNormal * diff
    -- move the character in order to resolve the collision
    pCharacter.translate(tVector,#world)
    end if
    end
    on keyDown
    -- check to see which key has been pressed
    -- and set the property relating to that key to TRUE
    if keypressed(123) then pLeftArrow = TRUE -- 123 = left
    arrow key
    if keypressed(124) then pRightArrow = TRUE -- 124 = right
    arrow key
    if keypressed(125) then pDownArrow = TRUE -- 125 = down
    arrow key
    if keypressed(126) then pUpArrow = TRUE -- 125 = up arrow
    key
    -- if 'r' key pressed, return character to starting position
    if keypressed("r") then resetCharacter
    -- if 'c' key is pressed, then switch camera
    if keypressed("c") then changeCamera
    end
    on keyUp
    -- when the arrow keys are released, set the properties to
    FALSE
    pLeftArrow = FALSE
    pRightArrow = FALSE
    pUpArrow = FALSE
    pDownArrow = FALSE
    end
    on exitFrame
    characterMove
    end
    on characterMove
    -- if the right arrow is pressed,
    -- rotate the character 5 degrees about the z-axis
    if pRightArrow then pCharacter.rotate(0,0,-5)
    --if the right arrow is pressed,
    -- rotate character -5 degrees about the z-axis
    if pLeftArrow then pCharacter.rotate(0,0,5)
    -- if the up arrow is pressed,
    -- move the character 5 pixels along the y-axis
    if pUpArrow then pCharacter.translate(0,5,0)
    -- if the down arrow is pressed,
    -- move the character -5 pixels along the y-axis
    if pDownArrow then pCharacter.translate(0,-5,0)
    -- move along terrain
    -- create reference for terrain (ground)
    terrain = p3Dmember.model("Terrain")
    -- store character's position
    charPos = pCharacter.worldPosition
    charPos.y = charPos.y - 20
    -- cast a ray down
    collisData =
    p3Dmember.modelsUnderRay(charPos,vector(0,0,-1),#detailed)
    -- if model is picked up on ray.
    if collisData.count then
    -- store total no of models detected by the ray
    totalCount = collisData.count
    repeat with modelNo = 1 to totalCount
    -- check if over the terrain model
    if (collisData[modelNo].model = terrain) then
    terrainPos = collisData[modelNo].isectPosition
    -- find out the distance the character should move up or
    down
    diff = (terrainPos.z - pCharacter.worldPosition.z)+45
    -- move the character
    pCharacter.translate(0,0,diff,#world)
    end if
    end repeat
    end if
    end

    ok,
    I have been trying to work this out for ahwile and I got
    pretty close on getting this correct but there are still some
    glitches. So far I did a little research in the help files to see
    what the dot product does and this is how I got my calculations
    going so far
    --the code
    on beginSprite me
    I created 2 spheres and a box. Next, I then positioned them
    so that the first sphere is alligned with the front end of the box
    and then I aligned the second sphere to back of the box. I will not
    show you the code of beginSprite because all this does is for
    creating the models and there are no calculations going inside this
    handler. In addition, with these 3 models, my purpose is to say
    lets prtend that the box is the chasis of the car and the sphere
    that is placed at the frent end of the chassis are to represemt the
    2 front wheels and the othere sphere is to represent the 2 back
    wheels of the car. Also, I initlalised a timer to the following
    below
    pTimer = (the milliseconds)
    end beginSprite
    ... note The timere is just for purposes of simulating a
    pretend upward movement for the wheels. See below which should
    explain it better then I can say it in words.
    --the code below is the calculations. The translations is for
    saying that I am pretending that the wheels are inclining up a
    hill. However, the wheels in the true game will be getting
    calculated by finding the distance of collion by using the
    modelsUnderRay function just like you normally would. By the way,
    all models and the camera are set to y is the up vector
    on exitFrame
    if ((the milliseconds) - pTimer) > 1000 then -- increment
    the calculations every one second
    pBall1.translate(0, 0.125, 0) -- This is for saying that
    this is the calculations that I am calculating the front wheels
    need to move up when they incline up the hill.
    pBall2.translate(0, -0.125, 0) -- Just like the front wheel
    pretend calulations but for the back wheels, and use a negative
    translate.
    pos1 = pBall1.transform.position -- get the calculated
    position for the front wheels
    pos2 = pBall2.transform.position -- get the calculated
    position for the back wheels
    norm1 = pos1.getnormalized() -- not sure I understand this,
    but in the help files, it says that when you calculate the dot
    product of 2 vectors that have been normalized, you then get their
    cosine
    norm2 = pos2.getNormalized() -- normalize the back wheels
    position
    dotProduct = norm1.dot(norm2) -- calculate the dot product
    of the 2 vectors
    pBox.rotate(dotAngle, 0, 0) -- I took a guess and thought
    that using the dotProduct will allow me to correctly rotate the
    chassis but the chassis is quite not rotating correctlly
    pTimer = (the milliseconds) -- update the timer so that we
    can recyle the above code again
    end if
    end exitFrame
    ... Ok, now like I said previously, the chassis is rotating
    almost correctlly, but if you continue to do this, and by after the
    third cycle, the front end wheels start to collide with the
    chassis. So in other words, the rotations look correct untill
    exitFrame is called for the third time and after which then the
    front wheels start to collide with the chassis.
    So I am wondering if anyone could help me out to fix this and
    explain what I am doing wrong?

  • Good collision detection?

    I have been looking into quadtrees since it is a way to detect collisions. Is there another better way to do this? My game also has a system of sorting sprites in an array based on there relative locations on the map. ie: my character can appear in front of a tree or behind it. I have a complex system to do this which tests polygons however I was wondering if there is an expert way to do this.

    well my tank game has two levels of collision detection. Well, I guess in a way it handles all the items in 3 levels.
    First level, I have a Vector storing the items on the screen. They're only evaluated in any way if they're in the Vector. I refresh that vector every 10 frames by testing all the objects in the game to see if they're in a rectangle that surrounds the screen.
    After that, to check collisions I have a simple distance formula check that finds the distance between the centers of two objects (ie. bullet and tank) and compares them to the sum of the largest dimensions (width for both) to see if they're close enough to collide.
    If that check returns true, it calls a third level of collision checking. This check intersects the areas I've created from polygons that outline my objects. This way even if they're rotated in any way, the check only returns true if there's an honest to goodness real accurate collision. This check takes much longer than the previous one, but since it has the first check behind it, this check isn't called very often.

  • Collision detection with rectangles

    Hi, I'm making a racing game from the top view. My track is made up of many gif files, each connecting to each other. My cars are also gif files, and the player's car doesn't move, it can only rotate by displaying gif files of the car in different angles. Only the track moves to create the effect of the car moving. I am having trouble with the collision detection when the car hits the side of the road and when it hits other cars. I've looked at the discussion by JTeen but my car are rectangles, not circles. Could someone please help me with the following:
    1. What is the best system to define the boundary of the road in the gif files.
    2. Should I use the 4 verties of the player's car to detect the collisions and change the co-ordinates whenever I rotate the car.
    3. My tracks are never actually curved, they are made up of multiple straight lines to create a turn. Should I use the slope of these lines and then create an equation for the lines for the detection?

    sure.
    btw this isn't the way of doing it, its simply a way of doing it.
    In a Sector based track, the track is represented as 2 polygons.
    An inner track edge, and an outer track edge.
    Both polygons have the same number of verticies.
    a screen shot from my track editor would probably explain it better than words... http://www.pkl.net/~rsc/4KApplet/editorGrab.png
    As the car goes around the track, you keep track of which sector it is in by doing a line intersection with either the nextSector or prevSector.
    The code will look something like this [taken from the 4KApplet]
                      //check for entry into the next sector
                      while(Line2D.linesIntersect(x,y,newX,newY,
                            trackX[RIGHT][newNext], trackY[RIGHT][newNext],
                            trackX[LEFT][newNext], trackY[LEFT][newNext]))
                         // if you do enter the next sector, this must loop, until you stop going forward in sectors
                         // if this loop wasn't here, a fast traveling car could potencially jump out of its current sector
                         if(newNext==1) lapChange--;//if the car passes the start/finish line, set the lapChange flag
                         newPrev = newNext; //newPrevious sector is now the old Next sector
                         newNext = (newNext+1)%SEGMENT_COUNT; //and the new next sector is the old next sector +1 (modded for track looping)
                         checkPrevious=false; //the car is going forward, so don't check previous sector gate line
                      if(checkPrevious)
                         //does same as above, but for previous sector
                         while(Line2D.linesIntersect(x,y,newX,newY,
                               trackX[RIGHT][newPrev], trackY[RIGHT][newPrev],
                               trackX[LEFT][newPrev], trackY[LEFT][newPrev]))
                            if(newPrev==1) lapChange++; //if the car is going backward, increment the lapCounter
                            newNext = newPrev;
                            newPrev = (newPrev + (SEGMENT_COUNT-1))%SEGMENT_COUNT;//backward looping by using mod as well :) didn't work this out until now!!
                      }Once you have determined which sector the car is in, you must then do 2 more line intersections to determine if the side of the track has been hit.
    In a Collision Map based track[n], you pre-calculate the 'inside-ness' of each pixel before hand and store it all in a [][], then, whenever you move the car, you simply look into the collisionMap [][] to see if the new point is track or wall.
    This has the advantage that you don't need to keep track of which sector the player is in (though you still have to do 1 line intersection to determine if the start/finish line has been crossed)

  • A better way to Double Click

    I have been wondering if there is a better way to detect single clicks Vs double clikcs than the model currently implemented. I am sure all of you have run into the problem of even though an event listener detects a double click eventually, it detects the single click first, so often you have to compromise the quality of your software to account for that. I have considered writing my own custom handler using threads and such, but it seems to me there must be a better way out there that I just have not been able to find. I need a way to detect double clicks, and fool the machine into believing no single click has occured. Must I re-invent the wheel?
    AC

    I agree that GUIs should have some uniformity to
    them..especially as we enter an age where computers
    are ubiquitous. But there are some situations where
    customized behavior is preferrable. If you have ever
    worked with movie special effects software, some art
    software, music software, especially, you know that to
    make a GUI intuitive, sometimes liberties must be
    taken with the 'standard' gui design.The application determines the standard not the OS nor the GUI.
    And to say 'Your code is not standard, therefore the
    fact that java cannont accurately distinguish between
    single and double clicks is your problem' smacks of
    nonsense to me.
    We all know that Java is a great
    language.Java is not just a language it is a platform and a philosophy.
    It is quicker and easier to program in,
    than c++, but it is not at full maturity. Every c++
    development environment I have ever used had the
    ability built in to distinguish between a true single
    click and a double click.As does Swing..
    I love Java, but most
    programmers could fill a page with the enhancements
    that it needs. Not all enhancements are practical.
    Like many I balked when I first started with Java at
    the fact that it did not have true multiple
    inheritence. I now realize that
    I never really needed it anyway. But some things, eg
    templates, I definitely could still use. That being,
    said, thanks for the dialog. Templates are a complicated horror, unless you really need your software to be truly adaptable you will never use them. Even MS, Sun and IBM disposed of that need a long time ago.

  • Is there a better way to stop a Method than Thread.stop()?

    First my basic problem. In one of my programs I am using constraint solver. I call the constraint solver with a set of constraints and it returns a Map with a satisfying assignment. In most cases this works in acceptable time ( less than 1 second). But in some cases it may take hours. Currently I am running the function in a Thread and using Thread.stop(). This look like that:
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
              WorkingThread t=new WorkingThread(constraints);
              t.setName("WorkingThread");
              t.start();
              try {
                   t.join(Configuration.MAX_TIME);
              } catch (InterruptedException e) {
              if(t.isAlive()){
                   t.stop();
              return t.getSolution();
         }where t.getSolution(); returns null if the Thread was interrupted.
    Unfortunately this sometimes crashes the JVM with:
    # A fatal error has been detected by the Java Runtime Environment:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006dbeb527, pid=5788, tid=4188
    # JRE version: 6.0_18-b07
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (16.0-b13 mixed mode windows-amd64 )
    # Problematic frame:
    # V  [jvm.dll+0x3fb527]
    # An error report file with more information is saved as:
    # F:\Eigene Dateien\Masterarbeit\workspace\JPF-Listener-Test\hs_err_pid5788.log
    # If you would like to submit a bug report, please visit:
    #   http://java.sun.com/webapps/bugreport/crash.jsp
    #Does anyone knows a better way to do it?
    Thank you in advance.
    Note 1: the Constraint solver is a Third Party tool and changing it is unfeasible. (I have tried it already)
    Note 2: Using Thread.stop(Throwable t) only chances the error message.

    In case somebody have the same problem here my code which solves the problem. Note it requires to parameters and the result to be serializable.
    The Class which starts to Process:
    public class Solver{
         public Map<String, Object> getConcreteModel(
                   Collection<Constraint> constraints) {
                   try
                        Process p=Runtime.getRuntime().exec(...); //do not forget the classpath
                        new TimeOut(Configuration.MAX_TIME, p).start();
                        ObjectOutputStream out=new ObjectOutputStream(p.getOutputStream());
                        new ErrReader(p.getErrorStream()).start();//not that std.err fills up the pipe
                        out.writeObject(constraints);
                        out.flush();
                        ObjectInputStream in=new ObjectInputStream(p.getInputStream());
                        return (Map<String, Object>) in.readObject();
                   catch(IOException e)
                        return null;
                   } catch (ClassNotFoundException e) {
                        //should not happen
                        return null;
         // For running in a own process
         static private class TimeOut extends Thread
              private int time;
              private Process p;
              public TimeOut(int time, Process p)
                   this.time=time;
                   this.p=p;
              @Override
              public void run() {
                   synchronized (this) {
                        try {
                             this.wait(time);
                        } catch (InterruptedException e) {
                   p.destroy();
         static class ErrReader extends Thread
             InputStream is;
             ErrReader(InputStream is)
                 this.is = is;
                 this.setDaemon(true);
             public void run()
                 try
                     InputStreamReader isr = new InputStreamReader(is);
                     BufferedReader br = new BufferedReader(isr);
                     String line=null;
                     while ( (line = br.readLine()) != null)
                         System.err.println(line);   
                     } catch (IOException ioe)
                         ioe.printStackTrace(); 
    }And the class which executet the Program
    public class SolverProcess {
          * @param args ignored
         public static void main(String[] args){
              try {
                   ObjectInputStream in =new ObjectInputStream(System.in);
                   SolverProcess p=new SolverProcess();
                   p.constraints=(Collection<Constraint>) in.readObject();
                   p.compute();
                   ObjectOutputStream out=new ObjectOutputStream(System.out);
                   out.writeObject(p.solution);
                   out.flush();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              //System.err.println("solved");
              System.exit(0);
         private Map<String, Object> solution=null;
         private Collection<Constraint> constraints;
           private void compute()
    }

  • URGENT: Collision Detection In Tiled Map

    HELP!!!!! I am creating a tile map of size 32*32. And the character image size is also 32*32. Now i am stuck in making collision with the walls. I have tried my own method but to no avail. Has anyone tried to doing collision detection? Need a simple logic method to detect the collision...
    (Using keyevent to control the character moving around)
    Pls I really appreciate your help!!!!!!!
    Thanks.....

    I assume you have some way of knowing that you need to display a wall tile on the map, so before you move a particular direction check to see if the square you will move to is an acceptable move (no wall, door, mountain, water etc). If it is unacceptable play a little sound or display a message, otherwise do the move.

  • 2D Pixel Collision detection on XML tiled map

    Hello,
    I'm designing a game where the player can move through a city composed of 2D image tiles. Right now we have successfully got the pixel collision detection to work on a large single image consisting of an invisible mask image and a visible image that shows a cluster of buildings and objects. The mask overlays the visible buildings and blocks / allows movement based on the color of the mask. Black is a collision, white is open space, etc.
    But this technique won't work for the game, since there will be many cities and vastly larger than this little testbed. I cannot create multiple huge cities into one file - the file would be several megs large, and I'm looking at dozens of cities.
    My idea is to create tiled maps, which will save the coordinates for the various building/object tiles in an XML file. However, I do not know how to make the collision detection work with such a tiled map. Moreover, I don't know if constructing a mosaic city using XML coordinates is the best way to go - I'm open for suggestions. My goal is to simply be able to assemble a city from individual tiles of buildings and masks, and drive/walk my character through the city with pixel collision detection, without using the current setup of a single image and a single mask.
    Any advice/suggestions offered will be GREATLY appreciated! This is our first Java project, but hopefully we can make this work.
    Thank you so much!
    Message was edited by:
    Gateway2007 - clarifying that this is a collision detection based on pixels, not planes or other method.

    Sound like this might be too late of a suggestion, but have you looked at Slick at all?
    http://slick.cokeandcode.com/static.php?page=features
    It might help with the tiling and collision aspects.

  • Managing multiple collision detection between objects(not necessarily circles)

    Hi.
    I´d like to know if there´s any good tutorial, or if somebody knows, a way, to manage a multiple collision detection with pixel level detection, for objects, not necessarily circles, irregular objects.
    Any help?

    Yes, and what about the speeds of each object?
    I was thinking something like this:
    var  _currentObj1SpeedX = obj1.speedX
    var  _currentObj1SpeedY = obj1.speedY
    obj1.speedX = obj1.speedX - obj2.speedX
    obj1.speedY = obj1.speedY - obj2.speedY
    obj2.speedX = obj2.speedX -  _currentObj1SpeedX
    obj2.speedY = obj2.speedY -  _currentObj1SpeedY
    Is it right?

  • [as1, as2] Complex Collision Detection, part 2

    Hello.
    I´d like to know, if there´s another way, not being the gskinner´s class, to
    do a complex collision detection, one that can check for collision between,
    two irregular shapes, without using too much of the processor.
    Thank you.

    You mean the bitmap data hittest method took too much processor power?
    Without knowing all your details it is hard to tailor an exact system and how it should work. So here is somewhat of how I would do it.
    I am assuming that you are trying to check if many things are hitting many other things and that the shapes, while irregular, are not wildly divergent from their bounding box. (In otherwords that they are neat shapes that are at least close to their bounding box, perhaps filling some 70% or so.) And I'm also assuming that they are not complex paths, e.g., not a doughnut/torus.
    Be sure to use a double loop that only tests the correct number of pairs. So if there are n items you will need n*(n-1)/2 trials. NOT n*(n-1). Very important here. Of course even this approach is a bit inefficient, and you could try the RDC algorithm (http://lab.polygonal.de/articles/recursive-dimensional-clustering/) But for smallish numbers of items the first approach is probably suitable.
    Use the basic bounding box hittest on all the pairs. For the pairs where there is a hit at that level put them in an array for further processing. This test is fairly quick and there is no point using a more expensive test on each pair. (As to the above RDC, I haven't read the whole thing closely for awhile, so this step might already be part of that algorithm)
    Take that array and use one of the other methods like the bitmap hittest or some version of the same algorithm of gskinners.
    Did you do all three of these things together or just #3? I don't know exactly how much speed you need, but some combination of these things should work fairly well.
    I'm still not really clear on why you don't want to use gskinner's class. Have you tried it and does it provide enough speed? Did you try kglad's method? Did it provide enough speed? I don't think either of those people would mind you trying out their algorithms to learn from -- just to see what is possible. (Sorry if I'm misrepresenting you there kglad! I plan to go back and find that bit of code just to see what clever tricks you are up to. )
    If you can't get enough speed with those algorithms, then how are you sure that is where the problem lies? Maybe there is something else that is sucking cycles? Just a thought.
    The other choice is to simplify some of your shapes to circles or other regular shapes.

  • Tile Based Collision Detection

    I am following Tonypa's Tile Based Tutorials and I have to
    say, they are great. He covers everything needed, except for one
    thing I am troubled on - Refering to Tutorial 9,
    http://www.tonypa.pri.ee/tbw/tut09.html,
    Stupid Enemy, instead of an enemy I want to make this a NPC who
    walks around in a village. So what do I do to make it so that I, or
    the char, doesn't walk right over the enemy/NPC? I am trying to
    develop an RPG, and it would look silly to have the character walk
    on top of the NPC. Can someone provided a snippet on how to make a
    collision detection with the NPC and not walk on top/under the NPC?
    One last favor to ask: What if I want to talk to the NPC if I
    am within a half tile? Would anyone be willing to share info on how
    this as well?
    Thanks a bunch in advance

    Ok, let me see if I get the read correct here: you have your scenery objects as tiles and when moving your players/NPC's through the scenery you are not scrolling the background as you go, but when you get to s certain point you want to scroll the tiles of the background also, so you can have new scenery cycle in as needed an still have the tiled background objects and new tiled background objects work for collision detection.
    If my take on your project is correct, then you have to make your tiles addressed with relative addressing formulas as you'll probably need to do with your sprites also.
    So the way this will go is that you have to make an offset and add them into your formula based on your character position. Then based on your character position you can choose to scroll your tiles left, right, up, down or what ever you choose to support. As a tile falls fully off the screen, you can dispose of it or cycle back through depending on how you implement your background.

  • Collisions detection in 3D environments

    Hi, all.
    Has anyone worked with collisions detection in 3D environments?
    I want to create an application in LabView for detecting collisions between 3D objects. I'm working with VRML models and the 3D Picture Control, but I'm open to other posibilities, if they are possible to be integrated into Labview.
    Thanks in advance.
    Regards,
    Francisco

    You may want to check out the new digital
    prototyping tools that just released. It is called the NI SoftMotion Module for SolidWorks and works with SolidWorks 2009 Service Pack 2.1 or higher and LabVIEW 2009 or higher. These tools connect accurate
    mechanical/physics simulation capabilities in SolidWorks with
    industrial-grade motion control software in LabVIEW. There are two ways you can perform collision detection using the tools:
    1. After the your motion control application is finished running, switch the scan engine to configuration mode. (To do this, right-click on My Computer >Utilities>Scan Engine Mode.) Then, in the SolidWorks motion study Motion Manager Toolbar, right-click on the top item in the tree (which has the same name as your assembly) and select Check Interference. Then click on the parts you want to check for collisions on, and select Find Now. If collisions occured, SolidWorks will tell you the time of the collisions and the volume of overlap.
    or 
    2. You can use a distance sensor to detect collisions. In this case, LabVIEW can monitor the sensor while the motion simulation is running and take action (such as stopping the move and alerting you) if the sensor value changes.  This also enables to to detect a "near miss" where the parts came too close for comfort but didn't actually collide. To include
    proximity sensor feedback in your LabVIEW control applications, add a
    dimension to your SolidWorks assembly and connecting it to a Measurement sensor in SolidWorks with an Alert configured
    (for example, alert if the distance is less than 5 mm). Then in
    LabVIEW, right-click on the SolidWorks assembly item in the LabVIEW
    project and select Map Sensors. For an example, launch the LabVIEW Example Finder (Help>Find Examples) and try running the shipping example called "Basic SolidWorks Sensors.lvproj".
    Here's some background information...
    NI
    SoftMotion for SolidWorks enables mechanical, electrical and control
    engineers to collaborate by creating a digital prototype of the motion
    control system that integrates mechanical simulation, motion control
    software, and sensor feedback. As soon as you have a CAD drawing, you
    can begin prototyping the machine design long before you incur the
    expense of building a physical machine. The new tools enable you to do
    thinks like:
    visualize realistic machine operation
    validate and iterate on the mechanical, control and electrical aspects of your design
    estimate the cycle time performance
    check for collisions or other programming mistakes
    calculate force/torque loads for stress analysis 
    select and size motor and mechanical transmission components
    improve communication between the engineers on your team and with customers
    deploy the validated motion control application to NI CompactRIO for use on the physical machine
    The following software versions are required:
    • LabVIEW 2009 (32-bit) or later
    • LabVIEW NI SoftMotion Module Standard or Premium
    • SolidWorks 2009 Service Pack 2.1 or later and SolidWorks Motion Simulation with the Motion Simulation add-in enabled from the Tools menu
    in SolidWorks. This is included with SolidWorks Premium, Simulation
    Premium, or Simulation Professional. When you enable the Motion
    Simulation add-in from the Add-Ins dialog box in SolidWorks,
    place a checkmark in both the left and right checkboxes so you don’t
    have to reenable the add-in each time you use NI SoftMotion for
    SolidWorks.
    For more information, visit this site:
    http://www.ni.com/digitalprototyping/
    Here's a few other resources to get you started. 
    LabVIEW-SolidWorks Digital Prototyping Training (see the topic called "Motion Control Timing and Sequencing")
    Getting Started Guide for NI SoftMotion for SolidWorks
    Here are links to the evaluation versions of LabVIEW and the NI SoftMotion Module for SolidWorks:
    LabVIEW 2009
    NI SoftMotion Module (includes a 30 day evaluation license for NI SoftMotion for SolidWorks)
    Contact your local SolidWorks reseller to purchase SolidWorks, upgrade your existing SolidWorks installation to SolidWorks Premium (which includes the required SolidWorks Motion Simulation capability), or to request an evaluation version of SolidWorks:
    http://www.solidworks.com/sw/contact.htm
    For information on deploying your motion control application to the NI CompactRIO programmable automation controller (PAC) platform, see this site:
    http://www.ni.com/motion/

  • Optimizing collision detection

    Hi,
    in a simulation I have to check for many collisions between
    multiple
    objects. So what I am doing is put a detection on each
    relevant
    movieclip that checks a list of objects (cars). When the
    number of
    objects is growing the number of loops is growing the same
    amount but
    the loops that checks for collision are growing too. So I am
    running
    into a preformace problem.
    I was thinking about how to optimize this performance
    problem.
    * first idea was to check only clips that are in a specific
    area. But
    this also creates an overhead on checking what area the clips
    are. I
    could create overlapping clips that are used to represent
    this areas and
    check if the clips are inside these areas.
    I am not quite sure if this is a real performance
    optimization or
    creates too much overhead.
    or
    * As I am also check for distance when colliding I could
    create a
    timeout for two clips that are too far away from each other
    and skip
    checking on next frame. But I am not sure how to create the
    conditions
    without creating a new big overhead.
    What I am using now is to exclude clips from any collision
    detection
    when they are moving out the scene and won't collide anyway.
    Anyone seen nice concepts and theories on optimizing complex
    collision
    detection?
    thanks for any help - if anyone understands what I was trying
    to tell ;)

    divide your collision region into sections that have are the
    size of your smallest object. assign each object to its current
    section. each section needs to retrieve the objects within it. you
    need a look-up table or easy way to determine adjacent sections.
    assign each section an id #.
    to efficiently detect pair-wise relations (like hittests)
    between all object pairs, check for relations between all objects
    in the section with the lowest id# and adjacent section. increment
    the id# and repeat.

  • Java3D collision detection (full test source)

    Hello!
    I have struggled with this problem for a month now, so I really need some help.
    I try to develop a game with collision detection with Java3D.
    To narrow it down I had made two test-java-files for you.
    File 1) Applet where I add all my objects (2 ColorCubes)
    File 2) A KeyListener to stear one of the cubes. The key listener also checks for collisons.
    All code is below, just compile and try.
    The idea is that the cube that I can stear should stop outside the other cube from any
    direction. But I can't detect that other cube at all.
    So if any one could try the code and give me some hints or example I would be most
    thankfull.
    Best regards
    Fredrik
    import java.applet.*;
    import java.awt.*;
    import java.awt.Frame;
    import java.awt.event.*;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.universe.*;
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.utils.behaviors.keyboard.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends Applet
         BranchGroup branchGroup;
         ColorCube colorCube1 = new ColorCube(0.4); //The cube that you can navigate
         ColorCube colorCube2 = new ColorCube(0.4);
         TransformGroup transformGroup1;
         public void init()
              setLayout(new BorderLayout());
              GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
              Canvas3D canvas3D = new Canvas3D(config);
              add("Center", canvas3D);
              SimpleUniverse simpleUniverse = new SimpleUniverse(canvas3D);
              branchGroup = new BranchGroup();
              //Cube1
              transformGroup1 = new TransformGroup();
              Transform3D transform3D1 = new Transform3D();
              transform3D1.set(new Vector3f(0.0f, 0.0f, -20.0f));
              transformGroup1.setTransform(transform3D1);
              transformGroup1.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
              //for setShapeBounds
              transformGroup1.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
              colorCube1.setCapability(Node.ALLOW_BOUNDS_READ);
              transformGroup1.setPickable(false);
              transformGroup1.addChild(colorCube1);
              branchGroup.addChild(transformGroup1);
              canvas3D.addKeyListener( new TestListener(transformGroup1, this) );
              //Cube2
              TransformGroup transformGroup2 = new TransformGroup();
              Transform3D transform3D2 = new Transform3D();
              transform3D2.set(new Vector3f(0.0f, 2.0f, -20.0f));
              transformGroup2.setTransform(transform3D2);
              colorCube2.setPickable(true);
              transformGroup2.addChild(colorCube2);
              branchGroup.addChild(transformGroup2);
              branchGroup.compile();
              simpleUniverse.addBranchGraph(branchGroup);
         public static void main(String[] args)
              Frame frame = new MainFrame(new Test(), 600, 400);
    }The KeyListener with Collision detection
    import java.awt.event.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import java.awt.Frame;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.picking.*;
    import com.sun.j3d.utils.geometry.*;
    public class TestListener implements KeyListener
         final static float DISTANCE      = 0.1f;
         final static double TURNANGLE      = 0.1;
         float x = 0.0f;
         float y = 0.0f;
         float z = -20.0f;
         private double angle = 0.0;
         TransformGroup transformGroup;
         Transform3D positionTransform3D = new Transform3D();
         Transform3D angleTransform3D = new Transform3D();
         Test test;
         PickTool pickTool;
         Point3d point3d;
         Vector3d vector3d;
         Transform3D transform3D;
         public TestListener(TransformGroup tfg, Test t)
              test = t;
              transformGroup = tfg;
              pickTool = new PickTool(test.branchGroup);
              pickTool.setCapabilities(test.colorCube2, PickTool.INTERSECT_FULL);
                pickTool.setMode( PickTool.BOUNDS );
              positionTransform3D.set(new Vector3f(x, y, z));
         public void keyTyped(KeyEvent e)
         public void keyPressed(KeyEvent e)
              if( e.getKeyCode() == KeyEvent.VK_UP )
                   if(isMovePossible(DISTANCE))
                        Transform3D temp = new Transform3D();
                     temp.set(new Vector3f(0, DISTANCE, 0));
                     positionTransform3D.mul(temp);
                     transformGroup.setTransform( positionTransform3D );
              else if( e.getKeyCode() == KeyEvent.VK_DOWN )
                   if(isMovePossible(-DISTANCE))
                        Transform3D temp = new Transform3D();
                     temp.set(new Vector3f(0, -DISTANCE, 0));
                     positionTransform3D.mul(temp);
                     transformGroup.setTransform( positionTransform3D );
              else if( e.getKeyCode() == KeyEvent.VK_LEFT )
                angle = angle + TURNANGLE;
                angleTransform3D.rotZ(TURNANGLE);
                positionTransform3D.mul(angleTransform3D);
                transformGroup.setTransform( positionTransform3D );
              else if( e.getKeyCode() == KeyEvent.VK_RIGHT )
                angle = angle - TURNANGLE;
                angleTransform3D.rotZ(-TURNANGLE);
                positionTransform3D.mul(angleTransform3D);
                transformGroup.setTransform( positionTransform3D );
         public void keyReleased(KeyEvent e)
         public boolean isMovePossible(float distance)
              boolean retValue = true;
              PickBounds pickBounds = new PickBounds( test.colorCube1.getBounds() );
              pickTool.setShape( pickBounds, getCordinate(test.transformGroup1) );
              PickResult pickResult = pickTool.pickAny( );
              if ( pickResult != null )
                   System.out.println("Boink");
                   retValue = false;
              else
                   retValue = true;
              return retValue;
         public static void main(String[] args)
              Frame frame = new MainFrame(new Test(), 600, 350);
        public Point3d getCordinate(TransformGroup transformGroup)
              Transform3D pointTransform3D = new Transform3D();
              transformGroup.getTransform( pointTransform3D );
              float[] cordinates = new float[16];
              pointTransform3D.get(cordinates);
              Point3d point = new Point3d(cordinates[3], cordinates[7], cordinates[11]);
              return point;
        public void printOutCordinates(TransformGroup transformGroup)
              Transform3D printOutTransform3D = new Transform3D();
              transformGroup.getTransform( printOutTransform3D );
              float[] cordinates = new float[16];
              printOutTransform3D.get(cordinates);
              for(int i = 0; i < cordinates.length; i++)
                   System.out.println(i + ":" + cordinates);
              System.out.println();

    First of all I would like to point out, that i've never actually used the PickTool, or in fact any element of the whole picking infrastructure from Java3D. Nevertheless I have done some collision detection in Java3D and it worked just fine. Unfortunatelly it required building the whole coldet ( collision detection ) algorythm from scratch :-)
    If You want to collide only two bodies then You probably should consider creating a special Behaviour class that will react to the WakeupOnCollisionEntry and WakeupOnCollisionExit criterions. There is a good example of such a behaviour class in the Java3D demos, under TickTockCollision. However if there will be more bodies in Your scene and they will collide with each other in a random way, then You should rather consider building the whole coldet engine from scratch ( it's not very difficult, but it takes some time )
    Either way, You could try to get a second opinion on the Java3D forum. People out there should have more experience with Java3D

  • Fly through camera collision detection

    i want my camera to have collision detection in its simplest
    form, i mean is there a way of saying to director this is the scene
    and this is the camera and wala all good.
    im using the fly through 3d action is it easier to setup with
    that.
    if not what way forward would you suggest for me
    i also want to perant an object to the camera so when it
    moves it moves two.
    thanks

    Collision detection for a camera is not trivial. Not only
    must you prevent the object that the camera is following from going
    through walls, but you must also prevent the camera from cutting
    through corners as it follows the object.
    You can find a demonstration of Camera Following behavior at
    http://nonlinear.openspark.com/tips/3D/followCamera/

Maybe you are looking for