So what I am trying to do is prevent a moving object from colliding into other objects. To do this, I am trying to move it a little bit at a time. If there is a collision, it moves back. It loops through this until it either moves the whole distance it needs to in one act, or if a collision is detected and it needs to move back slightly. It sounds good in theory, but when I try to implement the idea into my code it doesn't work as expected. I have tried coding it several times and each time it has failed. This is my current code (which kind of works but far from what I was hoping for):
Can anyone identify where my code is going wrong? Or perhaps it should be abandoned and I should try it from a different angle. Any advice is appreciated, thanks in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | private void move(){ double stepX = 0 , stepY = 0 ; //represents the amount that will be moved at a time, starts at 0 if (Math.abs(xSpeed) > Math.abs(ySpeed)){ //check if xSpeed is greater than ySpeed (in terms of absolute value) if (xSpeed > 0 ) stepX = 1 ; else stepX = - 1 ; stepY = stepX*(ySpeed/xSpeed); //multiplying by stepX insures that stepY is not altered by whether or not xSpeed is positive or negative for ( int i = 0 ; Math.abs(i) <= Math.abs(xSpeed); i += stepX){ if (getOneIntersectingObject(Actor. class )!= null ){ setRealLocation(getRealX() - stepX, getRealY() - stepY); setXSpeed(i); setYSpeed((i/stepX)*stepY); return ; } else setRealLocation(getRealX() + stepX, getRealY() + stepY); } } else { //same as above but modified for if (the absolute value of) ySpeed is bigger if (ySpeed > 0 ) stepY = 1 ; else stepY = - 1 ; stepX = stepY*(xSpeed/ySpeed); for ( int i = 0 ; Math.abs(i) <= Math.abs(ySpeed); i += stepY){ if (getOneIntersectingObject(Actor. class )!= null ){ setRealLocation(getRealX() - stepX, getRealY() - stepY); setXSpeed((i/stepY)*stepX); setYSpeed(i); return ; } else setRealLocation(getRealX() + stepX, getRealY() + stepY); } } } |