简体   繁体   中英

Collision detection and response with a square-square animation

Hey, I'm working on a mini 2D-animation in Javascript where you a moving cube and when you hit one of the edges of the view window, it should bounce off and continue moving(for example: a cube moving diagonally down, hits the bottom side of the view, then bounces up diagonally). 2 things I having a bit of trouble with is a) getting the damn cube to move, which I sure I would need to setInterval or something of the sort and b)The collision detection and response for the moving cube, which I figured you need to check the 4 sides of the cube and if they hit any of the sides, move accordingly. Any helpful hints and tutorials anyone can point me to would be appreciated. Thanks!!

UPDATE: Have the cube moving now just working on the collisions. My first attempt didnt work though it sounds correct in the mind. Any corrections are of course welcomed:

   if(x/left position of box > (width of window view - width of box)){

     go left

    } else if(x/left box pos < (width of window view + width of box)){

        go right

    } else if(y/top box pos > (height of view - height of box)){

        go down

    } else if(y/top box pos < (height of view + height of box)){

        go up

    } else {

        box.style.left = parseInt(box.style.left) + 2 + 'px';
        box.style.top = parseInt(box.style.top) + 5 + 'px';

    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM