java - Need advice on collision-handling -
i'm making 2d game, nil fancy, objects (called entities on) should collide eachother , terrain. now, detecting collision not problem, problem when entities collide terrain.
i have simple .png, upon loading game go through pixels of image , add together black ones list, these pixels collidable.
collision-code entity-class:
int ceiling = integer.max_value; int floor = 0; int rightpoint = 0; int leftpoint = integer.max_value; for(point p : main.terrain.points) if(gethyporect().contains(p)) { if(p.x > rightpoint && right) rightpoint = p.x; if(p.x < leftpoint && left) leftpoint = p.x; if(p.y < ceiling && up) ceiling = p.y; if(p.y > floor && down) floor = p.y; } if(rightpoint != 0) xcoord = rightpoint - sprite.getimage().getwidth(); else if(right) xcoord+=speed; if(leftpoint != integer.max_value) xcoord = leftpoint; else if(left) xcoord-=speed; if(ceiling != integer.max_value) ycoord = ceiling; else if(up) ycoord-=speed; if(floor != 0) ycoord = floor - sprite.getimage().getheight(); else if(down) ycoord+=speed;
in for-loop go through points (black pixels) in terrain, check if entity's collisionbox contains them (speed added in method, or rather "hypothetically" added, that's why has weird name). now, if x-value of point greater "rightpoint", , if entity walking right, it's overwritten. same happens leftpoint ("leftest" point), ceiling , floor. check if of these points have been changed, if have means collided terrain bounce them back. example, entity walking right , collided terrain, rightpoint have been written "rightest" point collided set coordinate entity right beside point collided with.
if 1 go @ 1 direction @ time, work perfectly, "weird" things happen when take multiple inputs account.
example: entity walks, flat floor, towards ledge on right, when entity halfway on ledge, wants go down, both right , downwards pressed, code check inputs, set entity wants , bounce if nail terrain, see press right , bounce entity end of ledge.
this own thought of how terraincollision work, couldn't find online except how check if collision took place, nil covers this. thought create solution work, or pointer how terraincollision should done?
your bouncing thought maybe problematic. seek instead ignore moves collide terrain: if player moves downwards , right, first check if downwards collide, if yes, ignore movement, , check right, if right possible right movement, else block, too.
java 2d user-input collision terrain
No comments:
Post a Comment