Redundancy Elimination?

L

Luc The Perverse

I just wrote this piece of code for moving an object given an intial
position, velocity and acceleration.

protected float X=0.0f;
protected float Y=0.0f;
protected float velX=0.0f;
protected float velY=0.0f;
protected float accX=0.0f;
protected float accY=100.0f; //gravity
protected float DesiredVelocityX=0.0f;

protected float ApplyDiscreteMovement(float Pos, float Vel, float Acc,
float Time){
return Pos + Time * Vel + Acc * Time * Time /2.0f;
}
protected float AdjustVelocity(float Vel, float Acc, float Time){
return Vel + Time * Acc;
}

public void MoveMe(float ElapsedTime){
if(accX>0){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if(velX>=DesiredVelocityX){ //reached desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
} else if(accX<0){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if(velX<=DesiredVelocityX){ //reached desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
}
velY = AdjustVelocity(velY, accY, ElapsedTime);
X = ApplyDiscreteMovement(X, velX, accX, ElapsedTime);
Y = ApplyDiscreteMovement(Y, velY, accY, ElapsedTime);
}

The redundancy that I am concerned about is in reaching the desired
velocity. I am using a nested if statement. First I check which way they
are accelerating to know whether to use a greater or lesser than in the
comparison to see if it has been reached or passed.

I was wondering if there were a better way to do this?

I don't want to multiple both velocities by the acceleration, this seems
like an unneccesary amount of overheard.

I did come up with this, but I think it further obfuscates the intent.

if(accX!=0.0f){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if((accX<0) == (velX<DesiredVelocityX)){ //passed desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
}

I realize that this is not identical since it isn't testing for velX ==
DesiredVelocityX, but as this is the only places where accX is even looked
at, it has the same effect.

Is there a better way to do this?
 
C

Chris Smith

Luc The Perverse said:
I just wrote this piece of code for moving an object given an intial
position, velocity and acceleration.
Okay.

I did come up with this, but I think it further obfuscates the intent.

if(accX!=0.0f){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if((accX<0) == (velX<DesiredVelocityX)){ //passed desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
}

The only thing unclear in that code is the if statement. If you like,
you can expand it:

if ( ((accX > 0) && (velX >= DesiredVelocityX))
|| ((accX < 0) && (velX <= DesiredVelocityX)))

or even:

boolean doneAccel = false;

if ((accX > 0) && (velX >= DesiredVelocityX)) doneAccel = true;
if ((accX < 0) && (velX <= DesiredVelocityX)) doneAccel = true;

if (doneAccel)
{
...
}

By the way, I can barely read your code. There are naming conventions
for a good reason... and, single-space indents?!? Do you even want
anyone to help you?

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

if(accX>0){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if(velX>=DesiredVelocityX){ //reached desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
} else if(accX<0){
velX = AdjustVelocity(velX, accX, ElapsedTime);
if(velX<=DesiredVelocityX){ //reached desired velocity
accX = 0.0f;
velX=DesiredVelocityX;
}
You gave three possibilities < 0, > 0, ==0

you currently do nothing on ==0;

You might factor like this if the 0 case comes out in the wash:

velx = adjustVelocity( velX, accX, elapseTime);
if (accX>0 ? velX >= desiredVelocityX : velX <= desiredVelocityX )
{
accX = 0.0f;
velX = desiredVelocityX;
}

note the corrections to the naming caps convention.
See http://mindprod.com/jgloss/codingconventions.html
 
C

Chris Uppal

Chris said:
[ ...] and, single-space indents?!?

Probably the result of pasting tabbed code into Outlook Express. My code comes
out the same way. Sometimes I clean it up (usually, if it's a short explanatory
snippet), sometimes I leave it as is (typcially if it's intended to be complete
code).

-- chris
 
L

Luc The Perverse

Chris Smith said:
The only thing unclear in that code is the if statement. If you like,
you can expand it:

if ( ((accX > 0) && (velX >= DesiredVelocityX))
|| ((accX < 0) && (velX <= DesiredVelocityX)))

or even:

boolean doneAccel = false;

if ((accX > 0) && (velX >= DesiredVelocityX)) doneAccel = true;
if ((accX < 0) && (velX <= DesiredVelocityX)) doneAccel = true;

if (doneAccel)
{
...
}

By the way, I can barely read your code. There are naming conventions
for a good reason... and, single-space indents?!? Do you even want
anyone to help you?

Thanks.

What you are seeing is an improvement in naming convetions. I used to use
single letters or letter number combos for names.

What capitalizing the first letter the only thing I did wrong?
 
L

Luc The Perverse

Chris Uppal said:
Chris said:
[ ...] and, single-space indents?!?

Probably the result of pasting tabbed code into Outlook Express. My code
comes
out the same way. Sometimes I clean it up (usually, if it's a short
explanatory
snippet), sometimes I leave it as is (typcially if it's intended to be
complete
code).

Yes that is what happened.

It was well formatted in notepad.
 
S

Scott Ellsworth

Luc The Perverse said:
First I check which way they
are accelerating to know whether to use a greater or lesser than in the
comparison to see if it has been reached or passed.

I was wondering if there were a better way to do this?

You could also use an abs.
if (Math.abs(velX)<desiredVelocityX){
do some stuff
}

This is not identical to what you have, but when I wrote n-body
simulators, I found it best to first determine the velocity,
acceleration, and position for the next time step, then the code that
checked the state for completion. I would also add the verification
code that the next time step had the same energy as the step I had just
done, which kept me from using an inaccurate method. (Note: if you
compute potential and kinetic, but allow inelastic collisions, you can
often take the difference in energy, and track it as the thermal energy
of the colliding objects.)

Scott
 
L

Luc The Perverse

Scott Ellsworth said:
You could also use an abs.
if (Math.abs(velX)<desiredVelocityX){
do some stuff
}

OMG duh!

I think this is the answer I was looking for.
This is not identical to what you have, but when I wrote n-body
simulators, I found it best to first determine the velocity,
acceleration, and position for the next time step, then the code that
checked the state for completion. I would also add the verification
code that the next time step had the same energy as the step I had just
done, which kept me from using an inaccurate method. (Note: if you
compute potential and kinetic, but allow inelastic collisions, you can
often take the difference in energy, and track it as the thermal energy
of the colliding objects.)

I think you are overestimating the physics of my sprite engine :)

I am still trying to find an efficent method for detecting collisions at
all. I'm trying to avoid using anything with an N^2 efficiency. I know if
I defined areas as rectangles, I could so some funky stuff like a binary
search tree with a quick sorting algorithm, and then compare min and maxes
to find collisions, but only if the discrete unit of measure is adequately
small that an object cannot jump over another object.

I'm thinking what I really need to do is have collision areas made with true
polygons, focusing on triangles and rectangles, and then stretch them
through 3 space (time) for each discrete movement, and look for the lowest Z
(time) value intersections in the planes and then recalculate with the
smaller time interval to calculate the position to enact an inelastic
collision.

My dilemma is, I don't know if all of that is necessary for a game. I can
reasonably assume that collision capible sprites, NPCs, PCs and Projectiles
will all be updated on a regular enough interval that there will be no
missed bullets. Forgive the pun, but I like my algorithms to be bullet
proof ;)

But as far as storing thermal energy, I don't know about that.
Conservation of energy in a simulated environment is not exactly a priority
AFAIC. Anyways, by definition, isn't all energy conserved kinetically in an
inelastic collision? (Or do I have it backwards?)
 
L

Luc The Perverse

Roedy Green said:
definitely better than my ternary operator solution. It reduces even
more redundancy.

Well . . assuming you are speeding up :( (I was actually trying to
implement it when I had this realization.)

It looks like there is no way to get away with just one simple comparison.

Although I think I am doing this the wrong way.

I think I need an abstract class called Movement with derived classes like
Walk and Stop which can be linked with hotkeys.

The real problem I have is that I am trying to make one part of the code do
too much
 
S

Scott Ellsworth

Luc The Perverse said:
OMG duh!

I think this is the answer I was looking for.

Cool - glad I could help.
I think you are overestimating the physics of my sprite engine :)

Check out the OReilly book 'physics for game developers'. C++ based,
but not hard to translate.
I am still trying to find an efficent method for detecting collisions at
all. I'm trying to avoid using anything with an N^2 efficiency. I know if
I defined areas as rectangles, I could so some funky stuff like a binary
search tree with a quick sorting algorithm, and then compare min and maxes
to find collisions, but only if the discrete unit of measure is adequately
small that an object cannot jump over another object.

I would approach this by:

Build a grid in your system.
This creates bounding boxes for your interactions.
Make sure that the boxes are sized such that an object may not go
completely through one box in one time step.
In other words, if the max speed is 300 m/s, and your time step is
1/30th of a second, then an item cannot move more than 10 meters.
Create 10 meter boxes

Place each item in the correct box based on its current position.
This is an o(n) operation, and can be done with a sparse structure

Iterate forward one step in time.
If an object did not leave its box
compare it with all objects that either started in or ended in its
box. This is n^2 in the number of items in the box, but that should be
small.
If an object moved to a new box
do the above for both boxes.

That comparison is done with a simple curve intersection algorithm, and
can be simplified to a line intersection if the time interval is small
enough. Under 1g, the straight line vs parabola approximation for
collision will be off by 5 mm.
I'm thinking what I really need to do is have collision areas made with true
polygons, focusing on triangles and rectangles, and then stretch them
through 3 space (time) for each discrete movement, and look for the lowest Z
(time) value intersections in the planes and then recalculate with the
smaller time interval to calculate the position to enact an inelastic
collision.

That also works, but I have found that the simple bounding box approx
works pretty well.
My dilemma is, I don't know if all of that is necessary for a game. I can
reasonably assume that collision capible sprites, NPCs, PCs and Projectiles
will all be updated on a regular enough interval that there will be no
missed bullets. Forgive the pun, but I like my algorithms to be bullet
proof ;)

But as far as storing thermal energy, I don't know about that.
Conservation of energy in a simulated environment is not exactly a priority
AFAIC. Anyways, by definition, isn't all energy conserved kinetically in an
inelastic collision? (Or do I have it backwards?)

<http://hyperphysics.phy-astr.gsu.edu/hbase/inecol.html>

"Macroscopic collisions are generally inelastic and do not conserve
kinetic energy, though of course the total energy is conserved"

If your calculations are off, you can lose energy. By tracking what is
lost to heat according to the physics (simple definition - what is not
potential or kinetic must be heat.) you can make sure that your
calculation engine did not give you something dumb.

Scott
 
R

Roedy Green

Check out the OReilly book 'physics for game developers'. C++ based,
but not hard to translate.

Perhaps if Newtonian physics were relabeled as realistic computer game
simulations, would the kids pay more attention?
 
L

Luc The Perverse

Roedy Green said:
Perhaps if Newtonian physics were relabeled as realistic computer game
simulations, would the kids pay more attention?

No.

The type of abstract thought that is required for benefitting from learning
something like physics is not something that can be forced. So many people
will back off instantly.

Although, it is possible there might be more effective methods of teaching
willing subjects
 
P

P.Hill

Scott said:
In other words, if the max speed is 300 m/s, and your time step is
1/30th of a second, then an item cannot move more than 10 meters.
Create 10 meter boxes

Careful about items that move from near the corner of one box across
the corner of a neighboring box into a third box. It can result
in items appearing to pass through each other.

One solution might be to just include the four boxes which
meet at the corner in your search. 1, 2, 3 or 4 boxes is still a
better set of objects then searching the entire gaming area, assuming
boxes are much smaller than the gaming area and assuming moving objects
don't cluster together.

Have fun,

-Paul
 
L

Luc The Perverse

P.Hill said:
Careful about items that move from near the corner of one box across
the corner of a neighboring box into a third box. It can result
in items appearing to pass through each other.

One solution might be to just include the four boxes which
meet at the corner in your search. 1, 2, 3 or 4 boxes is still a
better set of objects then searching the entire gaming area, assuming
boxes are much smaller than the gaming area and assuming moving objects
don't cluster together.

Have fun,

Of course, no matter how many boxes you have you are still adjusting by an
integer multiplier, and are going to run into trouble if your base algorithm
is of order n^2
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top