ok, silly question amateur programmer trying experiment way basic use of android graphics, here is.
in order familiarize myself 2d android graphics out friend of mine wants me use idea game, decided try , make simple version of pong. (simple meaning haven't made both paddles move yet)
going off of android api guides, built experimental application around custom view object (pongview
) has 3 shapedrawable
objects (rectangles
). 2 paddles (i called them sticks) , ball. implemented motioneventlistener
view , made left stick move (yay figured out :).
after that, made ball move using delayed runnable
created in main activity calls update method inside custom view. in update method, made collision handler reverses ball's vector (on specific axis) when hits sides of screen or sides of paddles.
but after playing around it, saw 1 of collision conditions not firing. ball pass through bottom , right side of stick, bouncing when hits left side or top.
here collision conditions:
//collisions if ((bx + bside == getmeasuredwidth() || bx == 0) || //hit right or left of screen ((bx + bside == lx || bx == lx + width) && (by < ly + height && > ly)) || //hit left stick ((bx + bside == rx || rx + width == bx) && (by < ry + height && > ry))) { //hit right stick bvectorx = -bvectorx; system.out.println("bounce x"); } if ((by + bside == getmeasuredheight() || == 0) || ((by + bside == ly || == ly + height) && (bx < lx + width && bx > lx)) || ((by + bside == ry || == ry + height) && (bx < rx + width && bx > rx))) { bvectory = -bvectory; system.out.println("bounce y"); }
- bside: side length (pixels) of ball square
- width: width of paddles
- height: height of paddles
- bvectorx: change in coordinate (pixels) per update on x-axis
- bx: x-coordinate of ball
- by: y-coordinate of ball
- lx: x-coordinate of left-paddle
trying narrow down problem area, commented out except statement statement giving me trouble (at least on x-axis):
bx == lx + width
i realized since lx
never changed during runtime, plug in raw value (75) testing , see if caused condition trigger. didn't. decided try 76 instead, , guess what, worked! have no idea why, worked. ball bounced @ line of pixels. tried putting variables in, trying:
bx == lx + width + 1 bx == lx + width - 1
and both worked! when took away 1 +/- 1 however, go right through paddle , bounce out hitting other side. (since reverse vector). want hit right side of paddle , reverse vector.
i have no idea why happening, in advance :)
edit: tested conditional , found these 2 pieces of code return true.
if (75 == 75) { int = 75; if (i == 75) {
but still never returns true.
if (bx == 75) {
thanks again support. :)
you should not checking exact equality i.e. if (bx == 75) {}
condition detect collision met only if bvectorx
had limited set of values (i.e. integers added or subtracted to/from bx
make value 75
).
just use <=
, >=
, should fine.
the same holds detecting collisions screen edges.