Java-Gaming.org Hi !
 Featured games (91) games approved by the League of Dukes Games in Showcase (757) Games in Android Showcase (229) games submitted by our members Games in WIP (843) games currently in development
 News: Read the Java Gaming Resources, or peek at the official Java tutorials
Pages: [1] 2 3 ... 5
 ignore  |  Print
 Mathematical vectors  (Read 44896 times) 0 Members and 1 Guest are viewing this topic.

Junior Devvie

 « Posted 2011-03-09 04:01:42 »

Hi everyone!

So here I am again requesting a bit of information and if possible some pseudo code to make me understand some vector theory.  Before fixing up collision detection (just a few corrections to do to make it function properly), I was wondering if I could use vectors for the current 2d top down car game I'm working on.

The vectors would be used for my car class, but the problem is I don't see how I would go along doing it.  I do know basic vector math and reading up on it for a memory refresh wouldn't be a problem.  The problem is when I try to think about it conceptually.  Basically I have my car - Friction would be a vector - and the motion itself would be a vector, but how would I go about calculating its new motion vector since I don't have the destination coordinates?  All I have is the acceleration which is being increased each update.  To my knowledge the to add vectors I would need current car coordinates + destination coordinates?

If someone could just nudge me in the right direction I'm sure I will be able to figure it out, since when I think about it all I think I would need is vector addition.  I think using vectors would give more depth to the application instead of using a simple scalar value such as currentSpeed.

Thanks!
pjt33

« JGO Spiffy Duke »

Medals: 40
Projects: 4
Exp: 7 years

 « Reply #1 - Posted 2011-03-09 09:03:15 »

You're already using vectors, but you're using two 1-D vectors rather than one 2-D vector.

Position: (x, y)
Speed: (vx, vy)
Acceleration: (ax, ay)

For a very simple quadrature mechanism:
(x, y) += (vx, vy) * dt
(vx, vy) += (ax, ay) * dt

There are, of course, better quadrature schemes. Which you use depends on the accuracy you want and the amount of computing power you have available. (I've used RK4 in one game, but that had a fairly complex physics model and I wanted the accuracy).
Eli Delventhal

JGO Kernel

Medals: 42
Projects: 11
Exp: 10 years

Game Engineer

 « Reply #2 - Posted 2011-03-09 17:08:38 »

Hmm... I wrote this last night but never pressed Post.

Just use 2D vectors for anything that happens in two dimensional space. Friction is not a vector, it's a single coefficient value (so one float), because it just applies against your current force, it has no direction.

Common 2D vectors I use for every entity:
- position
- velocity
- size

Acceleration is a 2D vector but it is usually applied by something else, not by the entity itself (for example gravity is applied by World on every entity).

Things that are not vectors:
- friction

Things that are 1D vectors (they have a length, but not a direction):
- rotational velocity
- rotation
- speed (speed is one dimensional, so is not a vector. You will never have both velocity and speed in one object, though. I will typically have speed in things that always move at a rate towards whichever direction they're facing)

See my work:
OTC Software
dishmoth
 « Reply #3 - Posted 2011-03-09 18:11:32 »

I know what you mean, but...

Things that are not vectors:
- friction

Friction is a force, hence a vector.  The Coefficient of Friction on the other hand is a scalar.  Of course in most games friction just means "slowy-downy effect" so you can define it however you like.
Simon

pjt33

« JGO Spiffy Duke »

Medals: 40
Projects: 4
Exp: 7 years

 « Reply #4 - Posted 2011-03-09 18:40:44 »

I know what you mean, but...

Things that are not vectors:
- friction

Friction is a force, hence a vector.  The Coefficient of Friction on the other hand is a scalar.  Of course in most games friction just means "slowy-downy effect" so you can define it however you like.
Simon
And if the aim is to be realistic then you need two coefficients of friction - one linear and one quadratic. Then you need to overdamp the frictional system to avoid getting harmonic motion just due to friction.

Junior Devvie

 « Reply #5 - Posted 2011-03-09 18:53:12 »

You're already using vectors, but you're using two 1-D vectors rather than one 2-D vector.

Position: (x, y)
Speed: (vx, vy)
Acceleration: (ax, ay)

For a very simple quadrature mechanism:
(x, y) += (vx, vy) * dt
(vx, vy) += (ax, ay) * dt

There are, of course, better quadrature schemes. Which you use depends on the accuracy you want and the amount of computing power you have available. (I've used RK4 in one game, but that had a fairly complex physics model and I wanted the accuracy).

I'll start off by saying in all honesty I don't know much of what you are talking about when you say 1D vector instead of 2D vector. (I'll venture a guess and say its 1D because it doesn't contain the full coordinate? I am probably totally off here)   When I look at the equations I'm thinking they are 2d right?  So that makes me think that x,y is a 2D vector because it has the full location? - If it is then I probably can go to 2D vectors pretty easily!

I actually re-read what Eli said, and the difference between 1D and 2D vectors is just that 1D doesn't have direction?

Hmm... I wrote this last night but never pressed Post.

Just use 2D vectors for anything that happens in two dimensional space. Friction is not a vector, it's a single coefficient value (so one float), because it just applies against your current force, it has no direction.

Common 2D vectors I use for every entity:
- position
- velocity
- size

Acceleration is a 2D vector but it is usually applied by something else, not by the entity itself (for example gravity is applied by World on every entity).

Things that are not vectors:
- friction

Things that are 1D vectors (they have a length, but not a direction):
- rotational velocity
- rotation
- speed (speed is one dimensional, so is not a vector. You will never have both velocity and speed in one object, though. I will typically have speed in things that always move at a rate towards whichever direction they're facing)

I'm trying to implement something as simple as velocity for example.  But if I'm correct about what pjt33 said about them 2D vectors then implementing it shouldn't be a problem!:).  As far friction not being a vector, I was thinking the exact way dishmoth described it

... Friction is a force, hence a vector.

And for rotation not being a vector I'm not totally sure about that, since the way I think about it, is having the rotationAngle can give me the updated direction? and I would use rotational velocity for its magnitude?  Or am I just confusing myself
Roquen

JGO Kernel

Medals: 517

 « Reply #6 - Posted 2011-03-10 11:17:42 »

WRT: 1D vectors.  These are scalars.  A 1D vector (if such a thing exists) would only exist in a one dimensional space.  From a linear algebra standpoint a n-d vector is a (1xn) or (nx1) matrix.  From a subspace standpoint they are 1-dimension subspace.  Form a geometric standpoint they are a direction and a magnitude.   So don't anyone run off and try to understand 1D vectors.

As a complete aside vector analysis can be quite confusing.  This is because the cross product of two vectors produces a bivector and not a vector.
pjt33

« JGO Spiffy Duke »

Medals: 40
Projects: 4
Exp: 7 years

 « Reply #7 - Posted 2011-03-10 13:05:44 »

WRT: 1D vectors.  These are scalars.
Not exactly, although notation is often abused to identify the two.
Roquen

JGO Kernel

Medals: 517

 « Reply #8 - Posted 2011-03-10 13:11:14 »

Opps.  What I intended to say is that the examples are scalars and not 1D vectors.  Not that scalars are 1D vectors.  Me bad.
t_larkworthy

Senior Devvie

Medals: 1
Projects: 1

 « Reply #9 - Posted 2011-03-10 15:55:32 »

hehe, math pedantry.

You can go into alot of detail about what-is-what. Vectors, scalars, pseudo-scalars, bivectors etc. are analogous to types in the math world. So a scalar and a pseudo-scalar can be written as a real number, but mean subtly different things. So some functions accept certain types, even though the number of reals are the same. For our purposes, the difference is how the value is interpreted in a geometric context.

Vectors are sometimes used just like arrays to collect math variables up (general use). In a geometric context a Euclidean vector denotes simultaneously a direction and a magnitude in a Euclidean vector space (what we are dealing with, 'normal' geometry).

Quote
And for rotation not being a vector I'm not totally sure about that, since the way I think about it, is having the rotationAngle can give me the updated direction? and I would use rotational velocity for its magnitude?  Or am I just confusing myself

Rotation is the classic example of where the subtleties creep in (in a Euclidean vector space).  So the angle between two vectors is a firm concept for a Euclidean vector space (in all dims), it always considered positive. The problem starts when you want a polarity attached. E.g. in 2D, what is the angle clockwise between vector A and B? The clockwise bit is an additional property of the vector space, which needs to be defined. So when you have angles against a global handedness of the space, your new signed angular quantity is something (subtly) different to the old one (even though both can be represented as reals).  So the signed version is a pseudo scalar whereas the first is a plain scalar.

So rotation is not really a vector quantity, in 2D is a pseudo scalar. In 3D it has three components, but they are related in a weird way and have their own type SO(3). You can't really call them vectors or psuedo vectors because they won't go into any function that normally accepts vectors and compute anything that makes sense.

All of this is not that important to know. We all have our own internal heuristics when we want to practically apply coding in geometric space. Mine is "rotation is a pain in the butt", and its the reason why we have to have the tan2 function in 2D (the quadrant aware version of tan), and quaternions in 3D. Whenever I find my rotation code is buggy or bloaty (like lots of ifs to determine an angle polarity), I start checking where I can use the tan2 function.

e.g. http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm

Runesketch: an Online CCG built on Google App Engine where players draw their cards and trade. Fight, draw or trade yourself to success.
Roquen

JGO Kernel

Medals: 517

 « Reply #10 - Posted 2011-03-10 16:30:23 »

Humm.  To me pedantry is more correctness for correctness sake.  Are you suggesting that it isn't both misleading and confusing to call values vectors when they are in fact scalars?
t_larkworthy

Senior Devvie

Medals: 1
Projects: 1

 « Reply #11 - Posted 2011-03-10 16:57:59 »

I am saying we can get bogged down in abstract math details which is not that important when implementing a car driving game. The difference between the types is nice to know, but doesn't really help point you in the right practical direction (tan2  <- not a mathematicians invention or naming convention).

Runesketch: an Online CCG built on Google App Engine where players draw their cards and trade. Fight, draw or trade yourself to success.
Eli Delventhal

JGO Kernel

Medals: 42
Projects: 11
Exp: 10 years

Game Engineer

 « Reply #12 - Posted 2011-03-10 22:19:45 »

I know what you mean, but...

Things that are not vectors:
- friction

Friction is a force, hence a vector.  The Coefficient of Friction on the other hand is a scalar.  Of course in most games friction just means "slowy-downy effect" so you can define it however you like.
Simon
Yes, I meant the coefficient of friction.

Also I just said 1D vector because pjt33 had already used that terminology and I wanted to avoid being confusing by calling it a scalar or float. Just keeping things consistent. I think we're getting way over deadly72's head.

See my work:
OTC Software

Junior Devvie

 « Reply #13 - Posted 2011-03-11 00:30:18 »

I know what you mean, but...

Things that are not vectors:
- friction

Friction is a force, hence a vector.  The Coefficient of Friction on the other hand is a scalar.  Of course in most games friction just means "slowy-downy effect" so you can define it however you like.
Simon
Yes, I meant the coefficient of friction.

Also I just said 1D vector because pjt33 had already used that terminology and I wanted to avoid being confusing by calling it a scalar or float. Just keeping things consistent. I think we're getting way over deadly72's head.

Actually I quite understand that , but what IS getting over my head is what t_larkworthy mentioned - I'm guessing its mostly abstract stuff, nothing in there that is too concrete.  In addition I'm a bit confused as to what Roquen means when talking about pedantry - but I do understand the difference between vectors and scalars.

I am on the other hand trying to incorporate using a mathematical vector class in my top down car project, but all I would need is abit of clarification to see if I'm headed in the right way?  For example this would just be my basic class.

 1  2  3  4  5  6  7  8  9  10  11  12  13 `public class Vector2D {   private double x;   private double y;      public Vector2D(double x, double y) {      this.x = x;      this.y = y;   }      public static Vector2D add(Vector2D v1, Vector2D v2) {      return new Vector2D(v1.x + v2.x, v1.y + v2.y);   }}`

and from that we declare a Vector2D position inside the car class which would be (x,y).  Then we apply the formulas

 1  2 `(x, y) += (vx, vy) * dt(vx, vy) += (ax, ay) * dt`

giving something like Vector2D newPosition = Vector2D.add(position, direction + ) that is where I get lost actually.  I'm using currentSpeed and it's not a vector (scalar value).  How do I split up currentSpeed to make it vx and vy? so i can multiply it with dt then add it to vector position.

that pjt33 was so kind enough to share
lhkbob

JGO Knight

Medals: 32

 « Reply #14 - Posted 2011-03-11 05:52:04 »

The magnitude of a 2D vector is sqrt(x^2 + y^2), and you "encode" speed in the vector by setting the vector's magnitude to the speed.  When you scale a vector's components by its length, you create a vector that is parallel to the original, but will have a length of 1.  Then if you multiply both x and y with a scalar, s, this newest vector has a length equal to s.

Example:
 1  2  3  4  5 `public void setLength(double length) {   double currentLength = Math.sqrt(x * x + y * y);   x *= length / currentLength;   y *= length / currentLength;}`

This updates a Vector2D to have the given length, which in the case of velocity is its speed. Besides looking at vector math, you're beginning to get into Newtonian physics and how to approximate it on a computer. That's why you have dt * velocity to get the change in position, and dt * acceleration to get the change in velocity.

pjt33

« JGO Spiffy Duke »

Medals: 40
Projects: 4
Exp: 7 years

 « Reply #15 - Posted 2011-03-11 07:17:21 »

 1  2  3  4  5  6  7  8  9  10  11  12  13 `public class Vector2D {   private double x;   private double y;      public Vector2D(double x, double y) {      this.x = x;      this.y = y;   }      public static Vector2D add(Vector2D v1, Vector2D v2) {      return new Vector2D(v1.x + v2.x, v1.y + v2.y);   }}`
You'll be making enough additions scaled by the timestep that it's worth having
 1  2  3  4  5  6  7  8  9  10 `   public static Vector2D add(Vector2D v1, Vector2D v2, double scale) {      return new Vector2D(v1.x + v2.x * scale, v1.y + v2.y * scale);   }        public double magnitude() { return Math.sqrt(x*x + y*y); }        public Vector2D scaleTo(double len) {            double s = len / magnitude();            return new Vector2D(x * s, y * s);        }`

Then the logic is something like
 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20 `    Vector2D x = new Vector2D(startx, starty);    Vector2D v = new Vector2D(0, 0);    Vector2D a = new Vector2D(0, 0);    while (!endOfLevel) {        x = Vector2D.add(x, v, dt);        v = Vector2D.add(v, a, dt);        // Acceleration: if key down then we accelerate in the direction we're facing.        // Keep it simple: facing in the direction of our speed        if (keyDown(KEY_ACCELERATE)) a = v.scaleTo(ACCELERATION);        else a = new Vector2D(0, 0);        // Need to apply friction to limit speed. Keep it simple: linear scaling only.        double speed = v.magnitude();        Vector2D friction = v.scaleTo(-speed * COEFF_FRICTION); // negative because opposes motion        a = Vector2D.add(a, friction);        // Render: since we said we're facing in the direction of our speed, need to rotate sprite by atan2(v.y, v.x)    }`

That will get you something which works. It can be improved in many ways, but better to start simple and then complicate it than to start complicated and never get anything working.
dishmoth
 « Reply #16 - Posted 2011-03-11 09:31:18 »

if (keyDown(KEY_ACCELERATE)) a = v.scaleTo(ACCELERATION);
Will crash (divide-by-zero) first time through because v is zero?

pjt33

« JGO Spiffy Duke »

Medals: 40
Projects: 4
Exp: 7 years

 « Reply #17 - Posted 2011-03-11 12:05:06 »

Will crash (divide-by-zero) first time through because v is zero?
Not crash but NaN. Good point.
Eli Delventhal

JGO Kernel

Medals: 42
Projects: 11
Exp: 10 years

Game Engineer

 « Reply #18 - Posted 2011-03-11 18:01:23 »

If it helps, I usually overload all my methods in my Vector2D classes to take either a Vector2D or a float.

 1  2  3  4  5  6  7  8  9  10  11 `public void scale(Vector2D otherVec){    x *= otherVec.x;    y *= otherVec.y;}public void scale(float scale){    x *= scale;    y *= scale;}`

My vector class actually has kind of a ridiculous number of functions. But once you write all of them you can then reuse them in every project from now on.

See my work:
OTC Software
IronclawsBt

Junior Devvie

Medals: 1

 « Reply #19 - Posted 2011-03-11 18:56:19 »

Another helpful thing can be to return the Vector that was modified. This allows you to chain functions like this: "v.add(1.0,0.0).normalize();".

It's not what you know, it's what other people think you know.
Just hope you don't get quizzed on it.
Game engine design tutorials

Junior Devvie

 « Reply #20 - Posted 2011-03-13 07:18:22 »

After having gone through http://forums.tigsource.com/index.php?topic=14154.0 I realize I may have jumped the gun by trying to implement vectors seeing as I still don't fully grasp the concept of a vector.  I understand that velocity, position, and from the article (acceleration?) is a vector with a direction and a magnitude but don't understand how that is possible (for velocity and acceleration) since we represent a vector as a point and not a scalar.  For example speed = velocity without the direction.  I don't understand how we can represent this. I mean how does velocity have a magnitude?   If I take a look at

 1 `currentSpeed = Math.min(+topspeed, currentSpeed + acceleration * deltaSeconds);`

currentSpeed is a scalar value.  This is what I use to represent velocity (or rather speed since there is no magnitude) in my game.  Can someone please fill in the missing blank?
philfrei
 « Reply #21 - Posted 2011-03-13 09:29:57 »

Holy smokes what a confusing thread!! Just to confirm, this has nothing to do with the Java Vector class, correct?

It seems to me like points in space are getting confused with magnitudes and directions. For example, a Point (3,4) is just a point in space, a location. But a Vector (3,4), pertains to the distance and direction from (0,0) to (3,4). The "Magnitude" of this Vector is 5, which can be calculated using the pythagorian formula, as the distance from (0,0) to (3,4). The "Direction" can be stated in either pi-radians or in degrees, usually involves something like an arctan function to derive it.

Velocity can be expressed as a Vector, it has a magnitude and a direction. Acceleration can be expressed as a Vector, it has a magnitude and a direction. Position (a point in space, the location at a given point in time for your spaceship or car or whatever) is NOT a Vector.

Maybe keeping these things straight will alleviate confusion. At least, I think I'm a little less confused now. I hope I didn't make things worse!

dishmoth
 « Reply #22 - Posted 2011-03-13 09:57:13 »

If I take a look at
 1 `currentSpeed = Math.min(+topspeed, currentSpeed + acceleration * deltaSeconds);`

currentSpeed is a scalar value.  This is what I use to represent velocity (or rather speed since there is no magnitude) in my game.  Can someone please fill in the missing blank?

In your car game the car always moves in the direction it is pointing.  You're storing the car's direction (carAngle) and speed (currentSpeed), and these together imply a velocity vector.

In the following, the velocity vector is (ax*currentSpeed, ay*currentSpeed).  (To throw in a bit more terminology, (ax,ay) is a unit vector.  Its magnitude is one, and it points in the direction of the car.)

 1  2  3  4 `double ax = Math.sin(Math.toRadians(carAngle));double ay = -Math.cos(Math.toRadians(carAngle));x += ax * currentSpeed * deltaSeconds;y += ay * currentSpeed * deltaSeconds;`

Eli Delventhal

JGO Kernel

Medals: 42
Projects: 11
Exp: 10 years

Game Engineer

 « Reply #23 - Posted 2011-03-14 17:56:35 »

Position (a point in space, the location at a given point in time for your spaceship or car or whatever) is NOT a Vector.
Yeah, this is a good point and an important conceptual distinction. I always use Vector2D's in memory to represent every point I might need because in terms of data members they are exactly the same. In addition, you often need to do the same operations on a Point that are done on Vector2D's (add, subtract, scale), and convert between them frequently. So in terms of code it makes sense to keep them the same.

If you really want the distinction, you can always make Point a subclass of Vector2D. Then you get both advantages.

See my work:
OTC Software
IronclawsBt

Junior Devvie

Medals: 1

 « Reply #24 - Posted 2011-03-14 18:56:50 »

Position (a point in space, the location at a given point in time for your spaceship or car or whatever) is NOT a Vector.

A position IS a vector. It is a direction and distance from an arbitrary point in space (the origin).

Edit: It may be more accurate to say you can define the position as a vector in the above way when using the Cartesian coordinate system..

It's not what you know, it's what other people think you know.
Just hope you don't get quizzed on it.
Game engine design tutorials
Riven

« JGO Overlord »

Medals: 1340
Projects: 4
Exp: 16 years

 « Reply #25 - Posted 2011-03-15 00:22:48 »

Position (a point in space, the location at a given point in time for your spaceship or car or whatever) is NOT a Vector.

A position IS a vector. It is a direction and distance from an arbitrary point in space (the origin).

I think you're mixing 'is a', 'has a' and 'is composed of'... further you're saying: "point = point + direction*distance", that is recursion

"a point can be described as a origin+vector", that doesn't mean that a point 'is a' vector, what you are describing is basically a transformation (only translating), which could just as well be a matrix.

"a plane can be described as a vector+distance", again, the 'is composed of' relation, as you can also describe a plane using two (non collinear) vectors, or a point+normal.

Hi, appreciate more people! Î£ â™¥ = Â¾
Learn how to award medals... and work your way up the social rankings!
IronclawsBt

Junior Devvie

Medals: 1

 « Reply #26 - Posted 2011-03-15 01:12:17 »

You can define a position as a offset from the origin (a vector) or as several values (a point). There are position vectors, also sometimes called a radius vector, and closely related with displacement vectors. If you are using Cartesian coordinates, these are all pretty much equivalent, but not necessarily so in any other basis.

It's not what you know, it's what other people think you know.
Just hope you don't get quizzed on it.
Game engine design tutorials

Junior Devvie

 « Reply #27 - Posted 2011-03-23 05:45:32 »

Ahhhh sorry it took so long guys, was a very busy week / weekend, haven't really had time to work on my project .  Anyway if I take a look at what you say dishmoth, and velocity is a unit vector (in my case) - does this mean that the length of velocity will always be 1? for instance it would always be one pixel in length(magnitude)?  In addition, when you tell me that velocity would be my carAngle which is direction and currentSpeed which is speed (which is not magnitude) how could this be a vector since I don't have a magnitude.  To me it would represent a Point.

About position though I'll be honest and say that I wouldn't get how it could be a vector, since there is no magnitude? This also would make more sense to me if it was only a Point. - since in neither case do I see a translation from the origin to the destination.

For velocity and position to be a vector they both need a magnitude if I understand the definition correctly.
dishmoth
 « Reply #28 - Posted 2011-03-23 09:42:35 »

Anyway if I take a look at what you say dishmoth, and velocity is a unit vector (in my case) - does this mean that the length of velocity will always be 1?

Well, I was saying that in your game (ax,ay) (not velocity) is a unit vector.  That vector always has length (magnitude) equal to one.  That vector is constructed so that it always points in the direction your car's facing.  You could call (ax,ay) the car's direction vector.  If you like, you can look at how that vector behaves as you turn the car by adding a line like the following to your code:
 1 `System.out.println("(" +ax + "," + ay + ") length=" + Math.sqrt(ax*ax+ay*ay)); // length should always be one`

Your velocity vector is constructed by multiplying (ax,ay) by the current speed.  That is, (vx,vy) = (currSpeed*ax,currSpeed*ay).  The direction of the velocity vector is the same as the direction of (ax,ay), i.e., the car's direction.  The length (magnitude) of the velocity vector is equal to the car's speed.  Again, you can look at what's happening in the code:
 1 `System.out.println("velocity length=" + Math.sqrt(vx*vx+vy*vy) + " speed=" + currSpeed); // both values should be the same `

Does that make sense?
Simon

philfrei
 « Reply #29 - Posted 2011-03-24 22:03:09 »

If you change position 1 pixel in the horizontal (X direction only) OR 1 pixel in the vertical (Y direction only) in a "frame", you are moving at a speed or velocity of 1 pixel per frame.

But if you go both 1 pixel X AND 1 pixel Y (45 degrees) in a "frame", you are moving at a speed or velocity of 1.4+ pixels per frame.

If you want to move 1 pixel, regardless of direction, (in other words, have a magnitude for your vector) you have to store your location as a float or double, and use trig to extract the X & Y components to get the next location. For example, if moving 1 pixel per frame with the direction of 45 degrees, X = 0.7+ and Y= 0.7+

as in

X = 1 * cos (45 degrees)
Y = 1 * sin (45 degrees)

X distance per frame = magnitude * cos(direction),
Y distance per frame = magnitude * sin(direction)