Show Posts

Pages: [1] 2

1

Game Development / Newbie & Debugging Questions / 2D topdown acceleration vectors

on: 20130330 05:01:01

Hi folks, been a while , quite a while actually, a few years I'd say ... life got in the way of programming what can I say.. . Anyway I came across an old unfinished project, a 2d topdown car game I was building... remembering a few of my topics http://www.javagaming.org/topics/carrotationproblemintopdown/23817/60/view.html and http://www.javagaming.org/topics/mathematicalvectors/23930/view.html, and well I must say that now I have been wanting to get a move on with the project; that is now that I have some free time on my hands! (work isn't being as invasive ) So I wanted to come back and solve the issue of movement once and for all... with all that I have learnt and read through, should be a piece of cake one would have thought... , seems it isn't the case. Having rummaged through my old thread, I remembered and found a link http://stackoverflow.com/questions/7312773/mathematicalvectorsandrotationstopdownjavagamedevphysicsproblem which explains how I wanted acceleration to act as a 2D vector. Moving on to the fact that the answer lies in the last post; that is having two vectors totaling to the acceleration vector (as i recalled being told a few times in my earlier posts on JGO), I am now faced with a simple yet unanswerable problem with the code I have used. The problem lies in the fact that considering an angle of 0 and 360 degrees both pointing north respectively, I cannot for the life of me figure out why moving up will not keep the angle constant to 0. (apart from the fact that this angle is given through Math.toDegrees(Math.atan2(y, x))) If we take this code for example ( a direct result of the last thread on stackoverflow ) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 double secondsElapsed = deltaTime / 1000.0;
double forwardDirection = velocity.angle() + 90; double leftDirection = forwardDirection + 90; double forwardAccel = 0; if (up) forwardAccel = 100; if (down) forwardAccel = 100; double leftAccel = 0; if (right) leftAccel = 100; if (left) leftAccel = 100; double fDir = Math.toRadians(forwardDirection  90); double lDir = Math.toRadians(leftDirection  90); Vector2D forwardUnitVector = new Vector2D (Math.cos(fDir), Math.sin(fDir)); Vector2D leftUnitVector = new Vector2D (Math.cos(lDir), Math.sin(lDir)); Vector2D acceleration = forwardUnitVector.scale(forwardAccel); acceleration.add(leftUnitVector.scale(leftAccel)); Vector2D deltaV = acceleration.scale(secondsElapsed); velocity.add(deltaV); position.add(velocity.scale(secondsElapsed)); angle = velocity.angle() + 90; 
the angle and motion with the upwards press is set to give acceleration on the x axis (which is fine considering my angle is 90 degrees pointing east). Now realizing that we want a forwardUnitVector of (0,1) (to get me poiting to the north) I was thinking something along the lines of a resulting degree of 270 (Math.sin(Math.toRadians(270)) = 1 which would be used along the y axis to create motion in the top direction. However, having set the forwardDirection to 360 which would give me a result of forwardUnitVector(0, 1) I am given a velocity and an angle which acts as a rotation and not a simple magnitude. Can anyone please exaplin to me why my concept of having motion towards the north is flawed? Thanks for bearing with me through this post! and if any other information is required let me know! deadly72



2

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110916 20:41:57

heheheh I believe this is exactly what I've been told quite a few times I think the issue that is confusing you is that the angle a car is rotated, or its direction, affects the direction that its motor accelerates the vehicle. When you press left/right keys you want to change the rotational acceleration and when you press up/down you want to change the translational acceleration.
I guess I wasn't clearing understand that rotation is totally seperate from acceleration. The part I don't understand from that is how they both interact to give the final position vector? I had created a thread on stack overflow and it's possible I just wanted to solve the problem asap so i reverted back to the old method of having a speed variable being increased by acceleration * deltaTime and then using this speed * math.cos/sin(dir) get my velocity vector. link to my question on stackoverflow: http://stackoverflow.com/questions/7312773/mathematicalvectorsandrotationstopdownjavagamedevphysicsproblemI really want to go back to the other way though  that is using an acceleration vector  but I'm unsure of how rotational acceleration and translational acceleration fit together to give the final position. In addition apparently using two vectors (I'm guessing the rotational and translational acceleration) would give increasingly bad results?  if you see the stackoverflow thread [in the situation where we have 2 vectors for acceleration] is that, in this one, the small errors mean that the speed will increase if you steer the car left and right, even if you don't touch the "up" key  whereas, in the other one, that sort of crosserror doesn't happen because we keep the speed and steering separate.
My reason to wanting to go back to using 2 vectors? If I ever want to implement drifting? apparently this is the way to go... sooo am I stuck between a rock and a hard place?



4

Java Game APIs & Engines / Java 2D / Re: Canvas drawing problem!

on: 20110910 03:53:03

You actually made me notice two things here. 1) The problem is intermittent on windows, I'm dev'ing on a linux box and here it doesn't show up. Only sometimes  which is a problem since I have no clue how to debug this!. On windows, it successfully renders like 9/10  but sometimes it fails.
2) I agree that the problem with the pack is really weird.  I think this may be somehow linked to problem 1, because on windows after many restarts  the menubar seems to pack also  leaving a white bar for the remainder of the canvas (Not really worried about this, since this is what I will be changing, that is more towards games having a centered menu)
In addition, I don't see why I would need the loop, that is something that really stumps me.



5

Java Game APIs & Engines / Java 2D / Re: Canvas drawing problem!

on: 20110910 03:33:39

I just set the gameFrame.setVisible(true) before the render() call > still doesn't draw . For now I actually don't need it in a loop, I'm using the loop as a running animation*, this is drawn before the loop for animation is called. About Toolkit.sync() didn't know that  I'll keep that in mind! Thanks!



6

Java Game APIs & Engines / Java 2D / [Solved] Canvas drawing problem!

on: 20110910 03:17:25

Hi guys! So I've been wanting to change the way my menu is going to be initialized and all  basically just remove all swing components, apart from maybe the jframe holding the canvas? Anyway, I've run into a snag, that is the Graphics2D object won't draw whatever I want it to draw. I think the problem lies in it only being painted once?  something that shouldn't matter? Here is the code linked to my problem. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
 private void init() { GUI gui = new GUI(); handler = new InputHandler(gui); gameFrame = new JFrame("ShootEm UP"); gameFrame.setLayout(null); gameFrame.setPreferredSize(new Dimension(CONST_WIDTH, CONST_HEIGHT)); gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gameFrame.setResizable(false); gameFrame.setIgnoreRepaint(true); designMenuBar(); canvas = new Canvas(); canvas.setBounds(0, 0, CONST_WIDTH, CONST_HEIGHT); canvas.setIgnoreRepaint(true); canvas.addMouseMotionListener(handler); canvas.addMouseListener(handler); canvas.addKeyListener(handler); gameFrame.add(canvas); gameFrame.pack(); canvas.createBufferStrategy(2); canvas.requestFocus();
render(); gameFrame.setVisible(true); }
public void render() { try { BufferStrategy bf = canvas.getBufferStrategy(); Graphics2D g = (Graphics2D) bf.getDrawGraphics(); test(g); g.dispose(); bf.show(); Toolkit.getDefaultToolkit().sync(); } catch (Exception e) { e.printStackTrace(); } } private void test(Graphics2D g) { g.setColor(Color.GREEN); g.drawString("LOL", 100, 100); g.fillRect(500, 500, 100, 100); } 
It's safe to rule out the gui variable, the handler variable and designMenuBar() function. Anyone got any ideas?



7

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110902 02:24:43

There are two directions you need to think about, the direction something is rotating and the direction something is sliding. The rotation and position of an object describe it. The rotation can be represented as an angle or as a direction vector that signals which way is front.
Basically, you are telling me here that rotation can be represented as a single double variable or a vector which has a magnitude of 1. I'm using a single double variable as pointed out earlier. In physics there are three principal concepts: acceleration, speed, and distance. Acceleration * dt will give you the change in speed, speed * dt will give you the change in distance. Velocity is speed in a multidimensional case.
The rotation of the object gets an acceleration, speed, and distance (amount of rotation) and the position of an object gets an acceleration, speed, and distance. These are all 2D vectors. The rotational acceleration, rotational velocity, and rotation are independent of normal acceleration, velocity and position except for a case I'll describe below.
This is a part I don't understand. How is rotational acceleration, rotational velocity and rotation independent of acceleration? Acceleration has the direction of that rotation, does it not? You're trying to simulate a vehicle. How you apply the physics to a vehicle can significantly impact how it "handles". In my vehicle model, the engine accelerates the vehicle forward in the direction its facing. This implies that you need to compute the rotation first, and then use the rotation to compute the positional acceleration since each frame it accelerates in the direction its facing.
You current situation that you've written up looks okay to me. You have implemented all of the concepts I've described. One thing to note is that you've collapsed the rotation equations down to a single dimension. This is 100% valid in your situation since you're turning about an objects center. Additionally, you've removed rotational acceleration so that turning is on or off (and when on will not speed up or slow down). This is also valid.
You are telling me that my current situation is valid here, yet my rotation has the problem of not being updated because my acceleration magnitude can be 0 when a user doesn't press up or down, which I have no idea how that can actually be correct. The rotation is not changing when the user is only pressing left or right arrow keys since my magnitude is 0 * Math.sin/cos(dir) == 0. How exactly do you represent the direction of acceleration if as you say, the rotation component of it all is separate from the acceleration? Additionally how do these two separate components interact with velocity and position? Like I mentioned isn't velocity dependent on acceleration * dt? (Note: acceleration is a vector...) Maybe some pseudo code would be of use here... I find it strange that acceleration and rotation are two different components when used in physics  since acceleration has a direction! lol (I know there is a lot of repetition here, but I just want to explain myself clearly) Oh and I want to thank you for sticking with me this long, I'm sure it's a pain, but I feel we are very close to the final result!



8

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110901 04:22:13

If you want to handle rotation, you need two acceleration vectors. One vector is the acceleration we've talked about before, which applies to translational velocity and affects the position of your vehicle.
The second vector is a rotational acceleration. It applies to how fast your rotational velocity is increasing. The rotational velocity changes the direction your car is attempting to travel. By splitting things into two vectors you can have things like drift where the car turns one direction and continues to slide the way it was originally going.
The direction of the acceleration vector is generally perpendicular to the direction you're heading, which is why I simplified it in my last post.
So let me clear something up then, this means we are creating a new velocity vector each update instead of simply adding the acceleration? I thought velocity just the added acceleration * dt each update? but essentially what I'm getting out of what you are telling me is velocity = new Vector2D(magvector, dirvector), which quite honestly I don't understand.. Right now the procedure is simple, as in my initial velocity vector is 0,0 and all I do is increase it by adding a new acceleration vector each update (which is scaled by time), leading to adding this to velocity vector to my position. Essentially I'm saying v = a * dt and p = v * dt. You are suggesting to switch this how exactly? I don't understand how you would manage to change/update the velocity without a single acceleration variable  that is the magnitude and the direction. This is the current situation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 double secondsElapsed = (deltaTime / 1000.0); double speed = velocity.magnitude(); double magnitude = 0; if (up) magnitude = 100.0; if (down) magnitude = 100.0; if (right) direction += rotationSpeed * (speed/topspeed); if (left) direction = rotationSpeed * (speed/topspeed);
double dir = Math.toRadians(direction  90); acceleration = new Vector2D(magnitude * Math.cos(dir), magnitude * Math.sin(dir)); Vector2D scaledA = acceleration.scale(secondsElapsed); velocity = velocity.add(scaledA);
if (speed < 1.5 && speed != 0) velocity.setLength(0); Vector2D scaledV = velocity.scale(secondsElapsed); position = position.add(scaledV); 



9

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110831 02:40:27

The thing is, I don't understand how the rotation occurs if we have a magnitude of 0. Acceleration cannot be 0 when changing direction or can it? So how do you handle this using a single acceleration vector? accompanied by a velocity vector and a position vector of course. Not that I don't want to use 2 accelerations, but tbh that would confuse me! since I wouldn't understand how to unite them for the final acceleration! Also as far as using an engine I'd rather have a shot at my own, that way once it's all worked out I'll be able to say I've created one and can move on to a more sophisticated one if I wish to do so I'm so close... yet sometimes it seems so far... I think once we've solved this rotation issue, motion won't be a problem anymore anywhere within this game



10

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110828 03:17:56

Seems you were right in saying that I don't need a stepping variable to increment acceleration  seeing as its constant* (It's the velocity that increases when we add acceleration! ) I actually have a problem with the rotation now that acceleration is fixed... dammit is it possible to get this over with! sheesh! So I know what the problem is but I actually have no idea how to fix it... 1 2 3 4 5 6 7 8 9 10 11 12 13 14
 double direction = Math.toRadians(carAngle  90); double speed = velocity.magnitude(); double magnitude = 0; if (up) magnitude = 100.0; if (down) magnitude = 100.0; if (right) carAngle += rotationSpeed * (speed/topspeed); if (left) carAngle = rotationSpeed * (speed/topspeed); acceleration = new Vector2D(magnitude * Math.cos(direction), magnitude * Math.sin(direction)); 
The problem is the acceleration vector. When I just turn the car, magnitude = 0 and 0*direction gives me 0 thus not updating the direction... I thought I could fix it with a simple if (speed > 0) acceleration = new Vector2D(speed * Math.cos(direction), speed * Math.sin(direction)) but that doesn't work and is obviously illogical.. seeing as we would keep adding the acceleration to velocity till velocity would hit MAX_VEL_LEN. Thoughts, ideas, suggestions? By the way I hate double posting but I really didn't want to make another topic on this subject regarding the same type of query this is, as I like related information to be kept concise and organised, and it has been a while..



11

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110809 04:49:35

I believe in my case having acceleration set to 0 while no keys are being touched is incorrect.  unless we apply friction to velocity and not acceleration (something i should just check actually*), but I fail to see the relation between this and a constant possibly*? being needed to calculate acceleration based on player input. Furthermore if the requirement to calculate acceleration does lead to having a new vector created each time the move function loops,  we DO need a step variable to increment acceleration since a car doesn't have constant acceleration  based on player input  if this efficient? Instead would it be possible of coming up with a way to deal with acceleration just based on vector functions?



12

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110809 02:35:21

I believe you're on the right track. The acceleration vector doesn't need to be constant. You were worried about what happens when it's not accelerating, then just have it set to (0, 0) (so it's length is 0 = no acceleration). I guess you would want to have some constant that describes the MAX_ACCELERATION_LENGTH (if the acceleration's length is larger than this, clamp it to that length, which would involve scaling the vector by MAX_ACCEL / length). You don't need a float variable storing current acceleration, that's what the vector is for. In your code, it looks like you've assigned your computed variables incorrectly. Instead of: 1 2 3 4
 acceleration = acceleration.scale(deltaSeconds); velocity = velocity.add(deltaV); velocity = velocity.scale(deltaSeconds); position = position.add(deltaP); 
you should have 1 2 3 4
 deltaV = acceleration.scale(deltaSeconds); velocity = velocity.add(deltaV); deltaP = velocity.scale(deltaSeconds); position = position.add(deltaP); 
Regarding your last question, if you want to set the magnitude of the acceleration vector without changing its direction, you divide the acceleration vector by its current length (so the new vector has a length equal to 1), then you scale it by your new acceleration magnitude. The resulting vector has the same direction as the old acceleration, but with the new magnitude. This does not work when the acceleration vector is (0, 0). At that point, you'd have to choose a direction as well. Ahhh right right, the first part was my mistake , I actually had: 1 2 3 4
 acceleration = acceleration.scale(deltaSeconds); velocity = velocity.add(acceleration); velocity = velocity.scale(deltaSeconds); position = position.add(velocity); 
The problem is actually increasing / decreasing the acceleration. Do I need a stepping varriable? IE. if (up) speed+= 5, and then in acceleration = new vector(speed* direction)? In addition the acceleration vector is set at zero in the beginning; How would I go about to setting up its direction if acceleration doesn't exist? It only goes at non zero while inside the move() function which is called by the update loop. This comes back to my original question which is do I need to create a new acceleration vector each loop  considering the player input? I think my problem lies with me still thinking in 1D instead of 2D... I just don't understand how you can increase/decrease acceleration without a constant.



13

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110808 05:26:39

This is one of those "don't worry about it now, but keep it in the back of your mind" kinda things. Simulation results will almost alway vary depending on the times of each step used (unless you way overcomplicate the computations..and then they still vary...so you start to pull out your hair)
I don't believe I'm ready just yet to turn to a fixed time step system, I'd rather understand how to fix what's wrong now and later on if need be do conversions Anyway following lhkbob's logic I've come up with the assumption that a new acceleration vector must be created when interacting with player input  thus giving me the following. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 double deltaSeconds = deltaTime / 1000.0; double speed = velocity.magnitude(); double direction = Math.toRadians(carAngle  90); if (up) acceleration = new Vector2D(75 * Math.cos(direction),75 * Math.sin(direction)); if (down) acceleration = new Vector2D(75 * Math.cos(direction),75 * Math.sin(direction)); if (right) carAngle += rotationSpeed * deltaSeconds * (speed/topspeed); if (left) carAngle = rotationSpeed * deltaSeconds * (speed/topspeed);
acceleration = acceleration.scale(deltaSeconds); velocity = velocity.add(deltaV); velocity = velocity.scale(deltaSeconds); position = position.add(deltaP); 
I believe that constant 75 would be used to describe the acceleration magnitude  but simulation wise is not the proper way of doing it. The car can accelerate and decelerate, thus meaning I need to figure out a way to increase/decrease acceleration respectively without creating a new vector each time the function is called. Would I need to add a step variable and increase/decrease it like I am doing it for the carAngle to determine the heading? Another note on the same topic, how would i set the direction of the acceleration vector if I am simply scaling or setting the magnitude of the acceleration variable without creating that vector using a direction?



14

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110807 05:30:38

You're using too many variables to store acceleration and velocity. You need: 1. a vector position (that is treated as a point) 2. a vector velocity (this is the direction of travel, and the speed, you get the speed by taking the length of the vector). 3. a vector acceleration (this is the direction of acceleration and the magnitude of acceleration, which you get from the length of the vector). You do not need a separate constant variable ACCELERATION or a vector direction (assuming you're keeping the vector velocity). To figure out how to update something every frame, we can look at the physics equations: These basically say that the change in velocity (v) over a period of time (t) is equal to the acceleration (a) multiplied with the time delta (t). Similarly, the change in position (d) over a period of time (t) is equal to the velocity (v) multiplied with the time delta (t). So if you're using vectors, it would look something like: 1 2 3 4
 Vector3 deltaV = acceleration.scale(dt); Vector3 totalV = velocity.add(deltaV); Vector3 deltaP = totalV.scale(dt); Vector3 finalP = position.add(deltaP); 
This is euler integration if you've ever seen that term used in your readings. Ahh right right, I thought I needed the constant acceleration variable to use it for the acceleration vector, since its initially started out as a zero vector. I'm guessing we can just set the acceleration vector to some constant digit?  But then that would mean its direction would be wrong?.. In addition I believe that the code you are giving me relates to objects which have a linear velocity. IE A bullet, the player has no control over its acceleration. In my case I do need to change the acceleration depending on if (up/down) and the direction on (right/left). To muddy the waters a bit, it's a good habit to run simulations at a fixed time rate. Although not important for very simple situations, it'll make make your life a lot easier when things get a little more involved.
Mind giving me an example of what I'm up against seeing as deltaTime is not *ALWAYS* constant (The majority of the time it is, but some discrepancy is probable).



15

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110806 02:42:36

Hi guys!, Finally back after a short leave from work . I've been working on the game for a while now  actually just adding features, recoding classes, using more efficient manners of doing things, and well I decided to get rid of my currentSpeed variable inside the car class. That means I'm left with a constant acceleration variable ACCELERATION, a vector acceleration, vector position, vector direction and vector velocity. Basically to get the speed now, we would use velocity.magnitude() now. The problem I'm having with this is in fact what pjt33 posted about acceleration being not a number when it's length is set to the constant acceleration * deltaTime from the initial velocity vector (0,0). Getting the magnitude from that vector and using the length to divide it is what gives me NaN, so I decided to just return a vector(length,length) and that just isn't the correct way to be doing it. Btw, sorry if this is considered grave digging, but I figured it still relates to a related problem I'm having.



16

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110409 01:36:09

hahaha, well I'm glad that's settled!, I fear I may have skipped through some code that would have been needed to figure out why direction isn't being reversed, so I'll post ALL the relevant parts now instead of omitting what I thought would be minor details. In my World class 1 2 3
 if (e.getBounds().intersects(wall)) { ((Car)e).scaleVelocity(1); ... 
which is (not too sure if that is correct) 1 2 3 4
 public void scaleVelocity(int scale) { velocity.scale(scale); position = Vector2D.add(position, velocity); } 
which leads to 2 methods inside my Vector2D class 1 2 3 4
 public void scale(int scaleFactor) { x *= scaleFactor; y *= scaleFactor; } 
and 1 2 3
 public static Vector2D add(Vector2D v1, Vector2D v2) { return new Vector2D(v1.x + v2.x, v1.y + v2.y); } 
I fear that my move method also plays a role into why the direction isn't reversed so here is the essentials. 1 2 3 4
 ... velocity = new Vector2D(magnitude * Math.cos(direction), magnitude * Math.sin(direction)); position = Vector2D.add(position, velocity); ... 
I'm thinking that because move is called every time update is called the scaled velocity vector gets ditched for the new velocity vector and thus I never see the change in direction occur. That's the best educated guess I can come up with, and I have no idea how to go about solving it. A second pair of eyes would really do me some good! Thanks!



17

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110408 02:13:11

Oops, I hadn't seen the negative sign before. (cos (angle), sin(angle)) is perpendicular to (sin(angle), cos(angle)). Your original code didn't have the negative, but deadly72 added it in (I'm not sure why). That may have been my fault. In deadly's original thread, that combination of sin and cos made the movement code consistent with the drawing code. Since the movement code was causing problems but the drawing code wasn't, it seemed more practical at the time not to bother debugging the drawing code, even though its use of angles was going against convention. The (sin,cos) in the movement code can be switched for the more conventional (cos,sin) so long as the rotation in the drawing code replaces carAngle with (carAngle+90) (errm, or possibly carAngle90) and the game's initial value of carAngle is similarly changed. Simon So this was fixed using the standard convention I suppose (cos, sin), by using 90 degrees on the carAngle's inital value. Does AffineTransform have the east facing as 0 degrees automatically? I see float vs doubles sparks a big debate, but after having skimmed through Orangy Tang's link I realized that it is really up to the programmers intuition to figure out whats best for the program. As for scaling the vector to change direction (1) I do understand what you mean now, so I'm guessing the problem is when I add the velocity vector to position that the desired effect isn't happening (or because I call the move method inside the class which create a new velocity vector and overwrites the one I scaled?). For example this is what's happening right now. 1 2 3 4
 public void scaleVelocity(int scale) { velocity.scale(scale); position = Vector2D.add(position, velocity); } 
velocity does reverse coordinates, but the position isn't reversing as expected? scale just multiplies the current vector by the scalar value. I'm at a loss as to why this isn't working out the way it's supposed to. EDIT: Oh and by the way, figuring out the direction was fixed. Stupid me was trying to get the direction the position vector instead of velocity vector



18

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110407 02:20:38

1
 To get the angle do I need to normalize the vector first? If so it should be pretty simple giving 
no, but do you notice it is radian not degree ? 1
 Oh, and a quick side note: I've seen so many people use floats instead of doubles for positioning. Whats the reasoning behind it and should I change the variables to represent floats instead? 
nowadays float is better suitable for hardware, but personnaly I prefer double as it give a lot higer resolution than float and enable NaN (matematical unresolvable) gesture I wasn't too sure about it being a radian or degree should have checked the api, my bad . Thanks for the info on the float. I wasn't sure about using it since it would just make a few operations require typcasting from double to float... so I guess I will just use doubles This was code ra4king gave you a bit ago and you've been using it since, but it has a bug in it. 1 2 3 4
 ... velocity = new Vector2D(Math.sin(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds), Math.cos(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds)); position = Vector2D.add(position, velocity); ... 
If you're creating an (a, b) vector from an angle (in this case, carAngle) and magnitude (in this case, currentSpeed * deltaSeconds) you want to have (a, b) = (magnitude * cos(angle), magnitude * sin(angle)) but right now you have them swapped and are using sin in your x coordinate's equation, and cos in your y's. As DzzD hinted at, Math.atan2 and Math.atan return angle values in radians and not degrees. If you want degrees, just use Math.toDegrees(Math.atan2(y, x)). Also, you do not need to normalize the vector before getting the angle. Math.atan and Math.atan2 both compute the arctan function, which in math takes a single scalar: arctan(y / x). If m is the magnitude of (x, y), then arctan( (y/m) / (x/m) ) = arctan( (y / x) * (1/m)/(1/m) ) = arctan(y / x) Math.atan2 separates the arguments so you don't accidentally divide by 0 and you can use the signs on y and x to determine which quadrant the angle should be in. Alright so getting the angle is fixed formula wise, but, but if I do the vector your way (with mag * cos(angle), and mag * sin(angle) for y ) my movement becomes messed up. For example pressing up and down keys now generate movement along the x axis instead of up and down respectively as they did before. If this is the proper way to do it, (and we can't emulate motion using up and down keys for north and south) then the only solution I can think of is that I need to change my sprite direction to face east at the beginning instead of north as it does currently. As far as why I added cos in the equation was for motion so when I pressed the up arrow the car would travel up the y axis instead of going down, as it does when you increase y.



19

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110406 21:22:29

should I use Vector2D to represent position and totally omit Point? Yes. should I use Vector2D to represent position and totally omit Point? Yes  it keeps the code a lot cleaner and less errorprone. Simply use sensible variable naming to remind you what things are. After all, it doesn't really matter how the data is stored, what matters is that you understand what the data represents. There are other advantages to doing things this way which I won't go into here but which you'll no doubt discover if you start to use vectors a lot! Alright, so I've changed the Vector2D class and the car class to only use Vectors and not Points as mentioned, and it does keep the code much cleaner and less error prone. So I've been trying to find out the direction in angles, as this is one of the main things that represents a vector! . My car is moving from the origin which is set through my car constructor Vector2D position = new Vector2D(40,480); and I believe I've hit a road block. The code is updated in my move method 1 2 3 4
 ... velocity = new Vector2D(Math.sin(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds), Math.cos(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds)); position = Vector2D.add(position, velocity); ... 
My understanding of the following two statements it seems hasn't sunk in. You can normalize any vector (except the zero vector) by dividing it by its magnitude: (c,d) = (a,b)/sqrt(a*a+b*b). The result is a unit vector. Any unit vector can be represented by an angle: (a,b) = (cos(theta),sin(theta)). The angle theta equals atan2(b,a).
To get the angle do I need to normalize the vector first? If so it should be pretty simple giving 1 2 3 4 5 6 7 8 9 10
 public Vector2D normalize() { double dummyx, dummyy; dummyx = x; dummyy = y; dummyx /= getMagnitude(); dummyy /= getMagnitude(); return new Vector2D(dummyx, dummyy); } 
the part that gets me confused is the next to get the angle. This is what I have 1 2 3
 public double getAngle() { return Math.atan2(y, x); } 
I'm pretty sure that is the problem with trying to find the angle because I'm getting bogus values. (and if normalization needs to occur first then it would be return Math.atan2(normalizedVector.y, normalizedVector.x)) ? In addition to getting the angle, I've been trying to figure out how to reverse the direction of the vector (Which should be simple!). From what I've read it seems that to reverse the direction a simple scaling operation on the vector with negative 1 should do the trick. Something around these lines? 1 2 3 4
 public void scale(int scaleFactor) { x *= scaleFactor; y *= scaleFactor; } 
I don't get how that works because if you scale a vector with negative 1 you will just have the resulting negative coordinates. I think once these two problems are solved I will see a light at then end of the tunnel, but till then I can't seem to figure out what is going on. Oh, and a quick side note: I've seen so many people use floats instead of doubles for positioning. Whats the reasoning behind it and should I change the variables to represent floats instead?



22

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110403 21:15:46

Alright, alright, so I think I've got it understood now that I fiddled with it/added it (Vectors and Points) to my code, thus ending up with position as a Point and velocity being a Vector. Having changed position to being a Point instead of a Vector causes a problem though and I can't seem to find out why. I think it has to do with setLocation(double x, double y) being converted to integers inside the Point class, but it causes a problem while I try to rotate the car. When position was a Vector I didn't have this problem, even when type casting and rounding the x and y in my car class. Here is a snippet of the current code. This is part of my move function inside the car class. 1 2
 velocity = new Vector2D(Math.sin(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds), Math.cos(Math.toRadians(carAngle)) * (currentSpeed * deltaSeconds)); position = Vector2D.add(position, velocity); 
This is the part of the Vector class. 1 2 3 4 5
 public static Point add(Point p, Vector2D v) { Point newP = new Point(); newP.setLocation(v.x + p.x, v.y + p.y); return newP; } 
and this is the part of the render function within my car class. 1 2 3 4 5 6
 AffineTransform savedAT = g.getTransform(); AffineTransform newAT = AffineTransform.getRotateInstance(Math.toRadians(carAngle), position.getX(), position.getY()); g.setTransform(newAT); g.drawImage(carImage, (int) Math.round(position.getX()), (int)Math.round(position.getY()), null); g.setTransform(savedAT); 
I'm pretty sure the rotation is messed up because of the getX() and getY() functions of the Point class, or it can be the problem when I use setLocation from the Point class in my car constructor... as follows 1 2 3 4 5 6 7 8
 public Car() { health = 100; score = 0; startX = 40.0; startY = 480.0; position = new Point(); position.setLocation(startX, startY); } 
Anyone got any thoughts as to why rotation is acting buggy?



23

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110327 05:11:48

@SimonH The example really helps clear up my misconception of vectors, and if I may be so bold to say so  would a simple 1 2 3
 public static Point add(Point p, Vector2D v) { return new Point(p.x + v.x, p.y + v.x); } 
be the conversion to add the vector to the point? I'd like one thing still cleared up though. Since a vector equals a direction and a magnitude, then isn't the following statement wrong? 1
 velocity = new Vector2D(direction.getX() * currentSpeed * deltaSeconds, direction.getY() * currentSpeed * deltaSeconds); 
Since there is no magnitude. Also that leaves me to believe that the constructor for Vector2D would need 3 parameters? Right now I only have x,y. I would need to add a third parameter that takes magnitude? @Kieran Thanks, but I have to be honest and say that SimonH's example was a clear explanation that now should keep making me think that a vector is how you move . But yea I'm thinking the same thing here when you  well everyone says  when you talk about velocity. I understand it has a direction but the magnitude is literally the problem. It is confusing me. I think of velocity in terms of a point. For example lets say we went ahead and said for a really basic rendering of the move method that x += 5, and y += 5. This makes me think that velocity = 5px/seconds for example, I don't see the connection to magnitude.



24

Game Development / Newbie & Debugging Questions / Re: easier way to implement this code;

on: 20110327 03:59:13

Try using
ImagePanel cards = new ImagePanel(new ImageIcon(getClass().getResource("back.jpg").getImage());
this should work if you are loading the files from a jar and if I'm not mistaken java will not allow you to read files outside an applet for security reasons. I know this is one of the reasons and I'm pretty sure it's related to how you are trying to read the file.
Good luck.



25

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110326 04:22:14

Alright dishmoth, I think I got the grasp of it, I'd just like a few of my thoughts ironed out. I understand that direction is a unit vector  and velocity is not since we keep adding the acceleration vector to it. Does this leave position to be a unit vector also? Since position doesn't really have a magnitude (unless its the size of the image?). I'm guessing I can test if it is a unit vector by simply printing out Math.sqrt(position.x * position.x + position.y * position.y). Is that what this formula is all about? giving the magnitude of a certain vector? I've changed how the car class works to interact with a Vector2D class but I'm not totally sure that I'm doing things the right way. I'll post a snippet of what I mean. This is the mathematical vector class 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 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); } public double getX() { return x; } public double getY() { return y; } } 
and some implementation in my car's movement method 1 2 3 4 5
 ... direction = new Vector2D(Math.sin(Math.toRadians(carAngle)), Math.cos(Math.toRadians(carAngle))); velocity = new Vector2D(direction.getX() * currentSpeed * deltaSeconds, direction.getY() * currentSpeed * deltaSeconds); position = Vector2D.add(velocity, position); ... 
and I still don't fully understand why everything except velocity can be considered a vector  instead of a Point? Or maybe a vector is just a Point with a direction? ahhh I'm so confused. The thing is I know once I can get the theory down the implementation would be no problem. Oh and by the way, philfrei I understand what you mean, this was taken care of in another thread I posted asking about top down rotation motion  thanks though!



27

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110323 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.



28

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110313 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?



29

Game Development / Newbie & Debugging Questions / Re: Movement Speed

on: 20110312 04:25:37

First determine how much time you want for that object to move 1pixel. Example you want it takes 2 seconds in every 1pixel move. Then see your delta update time and move your object on how much it need to move based on that time. I use this and move pretty smooth. 1 2 3
 public void move(long delta){ x += delta * speedOnMilisecond; } 
however, if your delta update time goes high, the animation will become choppy again as you said. So, you need to keep that delta small. This is more or less what you want done. Your update loop should be receiving the deltaTime it took to complete one loop in your game loop. For example I'm using 1
 update((int) ((currentUpdateTime  lastUpdateTime)/(1000*1000))); 
which I yanked up from http://www.javagaming.org/topics/basicgame/21919/view.html. It might be something to use as a reference for you to wrap the idea of using deltaTime to calculate your movement steps. It did take me a little while to understand how to get consistency between movement but once you understand the concept its actually pretty simple! Good luck!



30

Game Development / Newbie & Debugging Questions / Re: Mathematical vectors

on: 20110311 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 "slowydowny 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





Archive
(336 views)
20170427 17:45:51
buddyBro
(534 views)
20170405 03:38:00
CopyableCougar4
(977 views)
20170324 15:39:42
theagentd
(1013 views)
20170324 15:32:08
Rule
(992 views)
20170319 12:43:22
Rule
(972 views)
20170319 12:42:17
Rule
(971 views)
20170319 12:36:21
theagentd
(1070 views)
20170316 05:07:07
theagentd
(990 views)
20170315 22:37:06
theagentd
(759 views)
20170315 22:32:18

javagaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org

