I've written a fairly simple java application that allows you to drag your mouse and based on the length of the mouse drag you did, it will shoot a ball in that direction, bouncing off walls as it goes.
Here is a quick screenshot:
alt text http://img222.imageshack.us/img222/3179/ballbouncemf9.png
Each one of the circles on the screen is a Ball object. The balls movement is broken down into an x and y vector;
public class Ball {
public int xPos;
public int yPos;
public int xVector;
public int yVector;
public Ball(int xPos, int yPos, int xVector, int yVector) {
this.xPos = xPos;
this.yPos = yPos;
this.xVector = xVector;
this.yVector = yVector;
}
public void step()
{
posX += xVector;
posY += yVector;
checkCollisions();
}
public void checkCollisions()
{
// Check if we have collided with a wall
// If we have, take the negative of the appropriate vector
// Depending on which wall you hit
}
public void draw()
{
// draw our circle at it's position
}
}
This works great. All the balls bounce around and around from wall to wall.
However, I have decided that I want to be able to include the effects of gravity. I know that objects accelerate toward the earth at 9.8m/s but I don't directly know how this should translate into code. I realize that the yVector will be affected but my experimentation with this didn't have the desired effect I wanted.
Ideally, I would like to be able to add some gravity effect to this program and also allow the balls to bounce a few times before settling to the "ground."
How can I create this bouncing-elastic, gravity effect? How must I manipulate the speed vectors of the ball on each step? What must be done when it hits the "ground" so that I can allow it to bounce up again, but somewhat shorter then the previous time?
Any help is appreciated in pointing me in the right direction.
Thanks you for the comments everyone! It already is working great!
In my step() I am adding a gravity constant to my yVector like people suggested and this is my checkCollision():
public void checkCollision()
{
if (posX - radius < 0) // Left Wall?
{
posX = radius; // Place ball against edge
xVector = -(xVector * friction);
}
else if (posX + radius > rightBound) // Right Wall?
{
posX = rightBound - radius; // Place ball against edge
xVector = -(xVector * friction);
}
// Same for posY and yVector here.
}
However, the balls will continue to slide around/roll on the floor. I assume this is because I am simply taking a percentage (90%) of their vectors each bounce and it is never truly zero. Should I add in a check that if the xVector becomes a certain absolute value I should just change it to zero?
What you have to do is constantly subtract a small constant (something that represents your 9.8 m/s) from your yVector. When the ball is going down (yVector is already negative), this would make it go faster. When it's going up (yVector is positive) it would slow it down.
This would not account for friction, so the things should bounce pretty much for ever.
edit1:
To account for friction, whenever it reverses (and you reverse the sign), lower the absolute number a little. Like if it hits at yVector=-500, when you reverse the sign, make it +480 instead of +500. You should probably do the same thing to xVector to stop it from bouncing side-to-side.
edit2:
Also, if you want it to react to "air friction", reduce both vectors by a very small amount every adjustment.
edit3:
About the thing rolling around on the bottom forever--Depending on how high your numbers are, it could be one of two things. Either your numbers are large and it just seems to take forever to finish, or you are rounding and your Vectors are always 5 or something. (90% of 5 is 4.5, so it may round up to 5).
I'd print out a debug statement and see what the Vector numbers are like. If they go to somewhere around 5 and just stay there, then you can use a function that truncates your fraction to 4 instead of rounding back to 5. If it keeps on going down and eventually stops, then you might have to raise your friction coefficient.
If you can't find an easy "rounding" function, you could use (0.9 * Vector) - 1, subtracting 1 from your existing equation should do the same thing.
When the balls are all rolling around on the ground, yes, check to see if the velocity is below a certain minimum value and, if so, set it to zero. If you look at the physics behind this type of idealized motion and compare with what happens in the real world, you'll see that a single equation cannot be used to account for the fact that a real ball stops moving.
BTW, what you're doing is called the Euler method for numerical integration. It goes like this:
Start with the kinematic equations of motion:
x(t) = x0 + vx*t + 0.5*axt^2
y(t) = y0 + vyt + 0.5*ayt^2
vx(t) = vx0 + axt
vy(t) = vy0 + ay*t
Where x and y are position, vx and vy are velocity, ax and ay are acceleration, and t is time. x0, y0, vx0, and vy0 are the initial values.
This describes the motion of an object in the absence of any outside force.
Now apply gravity: ay = -9.8 m/s^2
To this point, there's no need to do anything tricky. We can solve for the position of each ball using this equation for any time.
Now add air friction: Since it's a spherical ball, we can assume it has a coefficient of friction c. There are typically two choices for how to model the air friction. It can be proportional to the velocity or to the square of velocity. Let's use the square:
ax = -cvx^2
ay = -cvy^2 - 9.8
Because the acceleration is now dependent on the velocity, which is not constant, we must integrate. This is bad, because there's no way to solve this by hand. We'll have to integrate numerically.
We take discrete time steps, dt. For Euler's method, we simply replace all occurances of t in the above equations with dt, and use the value from the previous timestep in place of the initial values, x0, y0, etc. So now our equations look like this (in pseudocode):
// Save previous values
xold = x;
yold = y;
vxold = vx;
vyold = vy;
// Update acceleration
ax = -cvxold^2;
ay = -cvyold^2 - 9.8;
// Update velocity
vx = vxold + axdt;
vy = vyold + aydt;
// Update position
x = xold + vxold*dt + 0.5*axdt^2;
y = yold + vyolddt + 0.5*ay*dt^2;
This is an approximation, so it won't be exactly correct, but it'll look OK. The problem is that for bigger timesteps, the error increases, so if we want to accurately model how a real ball would move, we'd have to use very tiny values for dt, which would cause problems with accuracy on a computer. To solve that, there are more complicated techniques. But if you just want to see behavior that looks like gravity and friction at the same time, then Euler's method is ok.
Every time slice you have to apply the effects of gravity by accelerating the ball in teh y downwards direction. As Bill K suggested, that's as simple as making a subtraction from your "yVector". When the ball hits the bottom, yVector = -yVector, so now it's moving upwards but still accelarating downwards. If you want to make the balls eventually stop bouncing, you need to make the collisions slightly inelastic, basically by removing some speed in the y-up direction, possibly by instead of "yVector = -yVector", make it "yVector = -0.9 * yVector".
public void step()
{
posX += xVector;
posY += yVector;
yVector += g //some constant representing 9.8
checkCollisions();
}
in checkCollisions(), you should invert and multiply yVector by a number between 0 and 1 when it bounces on the ground. This should give you the desired effect
It's a ballistic movement. So you got a linear movement on x-axis and an uniform accelerated movement on y-axis.
The basic idea is that the y-axis will follow the equation:
y = y0 + v0 * t + (0.5)*a*t^2
Or, in C code, for example:
float speed = 10.0f, acceleration = -9.8f, y = [whatever position];
y += speed*t + 0.5f*acceleration*t^2;
Where here I use tiem parametrization. But you could use Torricelli:
v = sqrt(v0^2 + 2*acceleration*(y-y0));
And, on this model, you must maintain the last values of v and y.
Finally, I've done something similar using the first model with dt (time's differential) being fixed at 1/60 second (60 FPS).
Well, both models give good real-like results, but sqrt(), for example, is expensive.
You really want to simulate what gravity does - all it does is create force that acts over time to change the velocity of an object. Every time you take a step, you change the velocity of your ball a little bit in order to "pull" it towards the bottom of the widget.
In order to deal with the no-friction / bouncing ball settles issue, you need to make the "ground" collision exert a different effect than just strict reflection - it should remove some amount of energy from the ball, making it bounce back at a smaller velocity after it hits the ground than it would otherwise.
Another thing that you generally want to do in these types of bouncy visualizations is give the ground some sideways friction as well, so that when it's hitting the ground all the time, it will eventually roll to a stop.
I agree with what "Bill K" said, and would add that if you want them to "settle" you will need to reduce the x and y vectors over time (apply resistance). This will have to be a very small amount at a time, so you may have to change your vectors from int to a floating point type, or only reduce them by 1 every few seconds.
What you want to do is change the values of xVector and yVector to simulate gravity and friction. This is really pretty simple to do. (Need to change all of your variables to floats. When it comes time to draw, just round the floats.)
In your step function, after updating the ball's position, you should do something like this:
yVector *= 0.95;
xVector *= 0.95;
yVector -= 2.0;
This scales the X and Y speed down slightly, allowing your balls to eventually stop moving, and then applies a constant downward "acceleration" to the Y value, which will accumulate faster than the "slowdown" and cause the balls to fall.
This is an approximation of what you really want to do. What you really want is to keep a vector representing the acceleration of your balls. Every step you would then dot product that vector with a constant gravity vector to slightly change the ball's acceleration. But I think that my be more complex than you want to get, unless you're looking for a more realistic physics simulation.
What must be done when it hits the
"ground" so that I can allow it to
bounce up again
If you assume a perfect collision (ie all the energy is conserved) all you have to do reverse the sign of one of the velocity scalar depending on which wall was hit.
For example if the ball hits the right or left walls revese the x scalar component and leave the the y scalar component the same:
this.xVector = -this.xVector;
If the ball hits the top or bottom walls reverse the y scalar component and leave the x scalar component the same:
this.yVector = -this.yVector;
but somewhat shorter then the previous
time?
In this scenario some of the energy will be lost in the collision with the wall so just add in a loss factor to take of some of the velocity each time the wall is hit:
double loss_factor = 0.99;
this.xVector = -(loss_factor * this.xVector);
this.yVector = -(loss_factor * this.yVector;
Related
I am using Sprite translate(xAmount, yAmount) method to move object by given offset. Is there a way to slow down this translation so that I can create smooth animation of moving objects. I could delay drawing in frames but that doesn't sound good approach.
eg. Code.
model.getSprite().translate(x, y);
Draw Code
model.getSprite().draw(game.batch);
You will have to draw it frame by frame, translating it a little bit at a time.
`
float sx=0.5f; // slow down translation factor in x axis by half
float sy=0.5f; // slow down translation factor in y axis by half
model.getSprite().translate(x*sx, y*sy);
`
For example:
if you want translation slow down only along x axis then set value of sy = 1 and value of sx from 0 to 1 where 0 results in no movement while .5 in half speed slow down.
If you want no change in translation speed set sx or sy value 1 , setting its value more than that will increase its speed.
Is there any way in cocos2d-x to detect collision force? I would like to make a different sound effects depending on collision force or disable sound effect at all in some cases.
For example: when I perform scaleTo action on my sprite that is lying on the ground, it starts changing it's size every moment and so it hits the ground every moment too. On every hit the application plays sound effect. I would like to play it only when my sprite falls from some real height.
Do you detect the collision in some update() function, isn't it? So, you need to remember object position on previous update() call. Something like this:
Vec2 previousPosition;
void YourClass::update(float dt)
{
…
this->detectCollision();
this->updatePhysics();
this->makeSomethingElse();
…
}
void YourClass::detectCollision()
{
currentPosition = yourObject->getPosition();
float distance = currentPosition.getDistance(previousPosition)
if (obstacleRect.intersectsRect(yourObjectRect))
{
// collide handler
if (distance == 0)
// do nothing
if (distance > threshold)
// play some sound
}
…
previousPosition = currentPosition;
…
}
Depends of distance between current and previous object location you can calculate object’s speed and estimate it force.
In your example, when object collides through ScaleTo, its position is stable, and distance and speed = 0.
If you move the object and the obstacle, the calculation of speed is more complicated and must be carried out according to the rules of vector addition
I've been trying to find out how to block the player from moving the correct way. However, the way I've been doing now, stops the player from moving at all.
I want the player to stop moving horizontally if it touches the side of the block's collisionArea, and if it touches the top or bottom of the block's collisionArea, I want it to stop moving vertically only. So that way you can still move up and down when you touch the side, and side to side when you touch top or botttom. Thanks.
if (player.collisionArea.hitTestObject(block.collisionArea))
{
player.y -= vy;
player.x -= vx;
}
Your basic approach is to move your object, test if the current position hits your obstacle, then move it back if it does. This could be adapted to separate out the x and y axis quite easily (reduced code for clarity):
player.x += vx;
if(player.hitTestObject(block)){
player.x -= vx;
}
player.y += vy;
if(player.hitTestObject(block)){
player.y -= vy;
}
However, there are potential problems with this. First of all, DisplayObject/x and y round their values to "twips", so your addition and subtraction of vx and vy will not necessarily result in the object landing back in the original position exactly. This can produce problems with objects getting stuck in walls and such. Sound strange? Try this:
var s:Sprite = new Sprite();
s.x = 1.1925;
trace(s.x); // 1.15
So, to avoid this, you can store the position separately instead of relying on the DisplayObject x and y property.
var oldPosition:Point = new Point(player.x, player.y);
player.x += vx;
if(player.hitTestObject(block)){
player.x = oldPosition.x;
}
player.y += vy;
if(player.hitTestObject(block)){
player.y = oldPosition.y;
}
Second, I thought I would just mention that while hitTestObject() is a convenient API to check the intersection of two display object bounding rectangles, in my experience when you mix it with movement and collision response it starts to break down, because it relies on the state of the display, which is subject to oddities like the twips rounding, and inflexible with timing (you can't, for example, project all your movements, then check collisions, since you need to move your display object to get a valid result from hitTestObject()). The better way IMO is to make collision detection purely math based, for example circle intersection/distance checks. All that hitTestObject() is really doing is Rectangle/intersects() based on display objects bounds anyway. Pure math based collision detection is more work to setup, but more flexible and in my experience more predictable. Just a thought for the future, perhaps!
First of all, this question is very genuine - Just for the next time, make sure you clarify the background of your question (i.e I`m making a game with an actionscript 2d graphics, blah blah blah).
Anyhow, I'll copy you a part of a code i written back in the day when i was into developing javascript games. Since i dont know how your objects are arranged, i`ll modify it in a way that'll just introduce the general algorithm.
// player: a class that holds an array of moves, and other relevant information. Varys on your program.
var optimizePosition = function (player) {
//after each time the player attempts to move, i check if he touches of the blocks. if he does, i move him back.
foreach(Block block in blocks)// replace this with an iterator for all the blocks
{
if (player.x-block.x < 32 || player.y-block.y < 32 ) // if player is touching a block:
undoLastMove(getLastMove(player),player);
}
// a little extra: always good to check if he's going out of the screen in the same function:
if(player.x > canvas.width - 64 || player.y > canvas.height - 64)
undoLastMove(getLastMove(player),player);
}
and each time the player moves, i call the function:
optimizePosition(player);
The content of undoLastMove(player) will contain the code you written above.
I have developed a simple basketball game. The ball can be thrown and bounces off the ground, walls, rim, and backboard. I would like to have a ball shadow appear when the ball gets close to the ground. I've done my research and am coming up with nothing. So far I have had a limited amount of success with the following, running in the update loop of course:
shadow.alpha = _activeBall.y/600;
shadow.x = _activeBall.x;
600 is the floor, the maximum y value the ball can fall. The code above gets me close, but the shadow is always present, even when I am high enough in the air that a shadow should not be seen. I tried something like this:
if( _activeBall.y > 450 ) shadow.alpha = _activeBall.y/600;
shadow.x = _activeBall.x;
but that pops the shadow in to abruptly. It would also be ideal if the scale of the shadow decreased as the ball moved away from the floor. I am stumped with the math with this one and was hoping someone here can recommend an approach for this. Come on math gurus! Whatcha got?
Ok, so you need to learn the skill of normalizing / rescaling. It's not tough, as long as you know what you want.
It looks like you want alpha to be 0 when _activeBall.y < 450, then go from something less than 450/600 to eventually 600/600. Since I don't know what you want your alpha to start at (0 or 0.25 seems logical), I'll just call it alpha0. The good news for algebra - it lets you use a variable. :-)
So, the first easy part:
if( _activeBall.y < 450 ) { shadow.alpha = 0; }
// I ALWAYS use {} in any control flow statement.
So, normalize the range you want - turn it into a number from 0 to 1. Do this by subtracting the initial value and multiplying by the total range.
var normalized = (_activeBall.y - 450) / (600 - 450);
Note the (), otherwise you'd calculate _activeBall.y - (450/150).
Now that you have the normalized value, apply it to your scale by doing the opposite function with your new scale - multiply it times the total range and add the initial value:
shadow.alpha = normalized * (1 - alpha0) + alpha0;
Incidentally, you can do similarly with the scale of the shadow, so that when it's higher up, it's smaller. The normalized value will still be the same, and you can just set the scaleX and scaleY with that value.
I'm writing a paint program that uses shape brushes to draw by using the matrix function.
Everything works well aside from the fact that it's not smooth at all. There will be gaps in the painting if the mouse is moved at a high speed.
I've looked everywhere but haven't been able to find any solution.
The code basically looks like this:
//Press mouse within container. Uses Matrix to draw instances of the brush.
private function handleMouseDown_drawContainer(e:MouseEvent):void
{
_matrix.identity();
_matrix.translate(mouseX - 10, mouseY - 30);
_layout.bitmapData.draw(_layout.brush, _matrix);
_layout.drawContainer.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove_drawContainer);
_layout.drawContainer.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp_drawContainer)
}
//Move mouse within container. Uses Matrix to draw instances of the brush.
private function handleMouseMove_drawContainer(e:MouseEvent):void
{
_matrix.identity();
_matrix.translate(mouseX - 10, mouseY - 30);
_layout.bitmapData.draw(_layout.brush, _matrix);
}
If anyone could help me figure out how to smooth out the drawing, I'd be forever grateful! =p
Thanks in advance.
You probably need some kind of interpolation between the mouse positions... there are of course many ways, I'll describe one very easy to implement but a bit hard to fine tune. Basically instead of drawing in each mouse position, you use an easing equation that follows the mouse with some delay... this way the described line will be a bit smoother, and will draw a few times between each mouse position.
So instead of doing (pseudocode):
onMouseMove {
draw(mouseX, mouseY);
}
You do something like:
x = 0;
y = 0;
onEnterFrame {
x += (mouseX - x) * 0.2;
y += (mouseY - y) * 0.2;
draw(x, y);
}
Although maybe what you really need is a way to limit the maximum distance between points, so if the mouse moves more in one frame, you interpolate points between the two positions and draw as many times as it's needed.
Or if you're looking for smoother lines (avoid sharp corners) maybe you also need to use beziers to control the resulting line.
Anyway, it all depends on the kind of drawing you're looking for.