Losing a bouncing ball's position
I'm trying to draw a Bouncing ball using WIN32 GUI, so i define a 2d vector for ball position and a rectangle map with my screen size
struct pos {
float x;
float y;
};
RECT maprect = {0, 0, 800, 600};
pos ballpos;
ballpos.x=300;
ballpos.y=300;
(of course im using a class for 2dvec and it's more than this)
and i draw a ellipse
Ellipse(backbufferDC, (int)ballpos.x-45, (int)ballpos.y-45,
(int)ballpos.x+45, (int)ballpos.y+45);
now to make my ellipse bounce i use this code in in my message loop and it works fine:
bool balldown = false;
if (ballpos.y > maprect.bottom-40) {
balldown = true;
}
else if (ballpos.y < maprect.top+300) {
balldown = false;
}
if (ballpos.y > maprect.bottom-40) {
balldown = true ;
}
else if(ballpos.y < maprect.top+300) {
balldown = false;
}
if (!balldown) {
vel+=1;
ballpos.y +=3;
}
else {
ballpos.y-=3;
}
Ellipse(bbdc, (int)tankpos.x-45, (int)tankpos.y-45,
(int)tankpos.x+45, (int)tankpos.y+45);
but to make it look more realistic i decided to change the ball velocity on the move so i end up with this code
float vel;
if (ballpos.y > maprect.bottom-40) {
balldown = true ;
}
else if (ballpos.y < maprect.top+300) {
balldown = false ;
}
if (!balldown) {
vel+=0.5f;
ballpos.y +=vel;
}
else {
vel-=0.5f;
ballpos.y-=vel;
}
Ellipse(bbdc, (int)tankpos.x-45, (int)tankpos.y-45,
(int)tankpos.x+45, (int)tankpos.y+45);
and it looks much better now, but the problem is the ball ju开发者_运维百科st bounces once, then the second time it goes into the ground and disappears!
if (!balldown) {
vel+=0.5f;
ballpos.y +=vel;
}
else {
vel-=0.5f;
ballpos.y-=vel;
}
This logic is wrong. Gravity always causes acceleration in the same direction, down.
What you should do is handle collision. An elastic collision with a massive wall could look like
vel = -vel;
So in the end you have
vel -= 0.5f;
ballpos.y += vel;
if (ballpos.y <= floory) {
vel = -vel;
ballpos.y = 2*floory - ballpos.y;
}
else {
vel-=0.5f;
ballpos.y-=vel;
}
You might be getting the negative values here.
精彩评论