I feel like the solution is very simple, but in all honestly I failed math multiple times in high school, so I'm barely grasping even the basic concepts right now.
The idea is very simple.. I want to have a bunch of graphical objects tween animate from one side of a 300x300px div to the other side along randomized curved paths as if they were being tossed or dropped from the top left to the bottom right (and vice versa, back and forth).
I know I need to use some form of Trigonometry to solve this (sin, cos, tan??). I also already know how to get my two points (randomizing Y points, and then randomly putting x points on the positive or negative side of the 300px width). But the part where I have to actually calculate steps along a curve is beyond me.
Here's a crappy diagram of basically what I'm attempting.. I searched Google but all of the examples were way overcomplicated or too abstract. I just want to learn how to make a curve between two points.. That's it!
So simple question: How do I randomize a curved animation (or plot points along a curve) between two points using vanilla JavaScript (no JQuery please).
First of all, if you would like a quick look into the math of JavaScript animations , you might consider visiting this link
Actually, you only need very simple trigonometry (sine and cosine). If you are tossing something from a point (X0, Y0), the equations of motion are more like a parabolic trajectory.
From Wikipedia:
Displacement and coordinates of parabolic throwing
At any time t, the projectile's horizontal and vertical displacement
are:
x = X0 + v0 * t * cos(theta)
y = Y0 + v0 * t * sin(theta) − 0.5 * g * t * t
So there you go, your coordinates in pixels for every t time step.
You may define theta and v0 as constants or also as random values to make the animation more chaotic and lively.
Play with the value of g (in Earth it is 9.8 m/s²), because probably when scaling to pixels/s² it might overshoot.
Also you may want to give negative values to X0 and Y0 in order to intercept the descending part of the trajectories, leaving the ascending out of the div.
Related
I don't understand authors login when calculating collisions between two circles (bubbles). Here is the Calculating collisions section.
Author writes:
The bubble being fired follows a set of coordinates defined by the
equations:
px = ex + tdx py = ey + tdy
where px and py are points on the trajectory of the bubble’s center
point. The calculation of px and py happens in jQuery’s animate method
and is the standard equation for moving a point along a line. Next,
we’ll calculate t at the closest point on this line to the center of
the bubble that we’re checking against:
var t = dx * distToBubble.x + dy * distToBubble.y;
I don't understand what t is and why it calculates by the following formula:
var t = dx * distToBubble.x + dy * distToBubble.y;?
This has little or nothing to do with programming, it is absolutely Math. So I think this question shouldn't be here, but I will answer it just for helping you out.
I don't understand what is t
The line of movement of the bubble being fired is defined by a parametric equation, wich parameter is the variable t
why it calculates by the following formula
This is kind of complex, the book just shows the final result of the following calculation. There is a formula to calculate the distance between a point and a line. In this case the point is the center of the target bubble and the line is represented by the parametric equiation previously shown. After you solve that, you can derive that equation to find the minimum distance.
Although there is an easier way to solve this. Using dot product between the origin of the target bubble and the coordinates of the shooted bubble with the parametric function and equal it to 0 (perpendicular intersection) you cand find the value for t.
The important point here is that the book already solved the problem for you and it is showing the final result so you can use it.
Good luck with your game!
I have a function which should be finding the middle of two radians
function mrad(rb,ra){return (rb+ra)/2;}
But sometimes when I plot the x and y with Math.sin and Math.cos the two a specified length the new coordinates are coming out at the polar opposites of what I intend.
for example; If I expect the new points to be down and to the right sometimes they are coming out as up and to the left. The coordinates are correct apart from this!
Here is how I plot the new x and y
xnew=xold-(100)*Math.cos(radian);
xnew=yold+(100)*Math.sin(radian);
I am guessing that it might matter if radian B (rb) is bigger than ra. I think what is happening is that I am going full circle in this case, whereas I sometimes should be instead doing something like
function mrad(rb,ra){return (rb-ra)/2;}
My questions are
Is my assumption correct?
What would be the condition, how to tell when to do rb-ra vs rb+ra, or to put it better, how do you tell if one radian is pointing above or bellow the other?
It should look something like this
function mrad(rb,ra){return ((/*condition*/)?(rb-ra):(rb-ra))/2;}
Edit
To find the range I have tried to express different values to find a range in radians but cannot find anything more than a diagonal line
http://jsfiddle.net/roLLqfs6/
Also the defined length is not always 100 as it is written in the example
It's really a maths question. You need to make sure that your angles are in the same range (either -pi ... pi or 0 ... 2.0 * pi), but even then, taking the mean of them will not necessarily find the angle you are looking for - you might expect that (in degrees, for simplicity) the answer you want for 10º & 20º would be 15º, but what would you expect for 175º and -175º? I suspect you would want 180º (as this is the minor arc between them), but you will get 0º.
So, you need to test the difference, to see that they are less than 180º (pi radians) apart, and modify the answer accordingly if they are not.
I have recently started playing with canvas after seeing how easy it can be. My first project was just to keep a circle in its boundaries as it moves around. I made a few more things involving the movement of circles and now...
I'm currently working on bouncing two circles off of each other when they hit. You can see the example of that here: http://jsfiddle.net/shawn31313/QQMgm/7/
However, I would like to use a little more real world physics. At the moment, when the circles hit each other they just reverse their path.
As shown here:
// Dont be confused, this is just the Distance Formula
// We compare the distance of the two circles centers to the sum of the radii of the two
// circles. This is because we want to check when they hit each other on the surface
// and not the center.
var distance = Math.sqrt(Math.pow(c1.x - c2.x, 2) + Math.pow(c1.y - c2.y, 2));
var r1 = c1.rad;
var r2 = c2.rad;
if (distance < r1 + r2) {
// Change the slope of both circle
// I would like to figure out a more effecience way of bouncing the circles back
// However, I have no idea how to determine the angle the ball was struck,
// and with that information bounce it off at that angle
c1.xi = -c1.xi; // path is reversed
c1.yi = -c1.yi;
c2.xi = -c1.xi;
c2.yi = -c1.yi;
}
However, I would like the circles to go in opposite direction determined by the point and angle of intersection.
I am only in the 9th grade and not sure how the formula for something like this would look. But I know that it is possible because this kind of physics is present in many games. An example would be an 8-ball game. When the balls hit each other, they move across the table according to how the balls hit each other.
I would appreciate any tips on how to do this or if I should wait until I have a stronger understanding of Physics and Math in general.
too bad we can't draw a very simple scheme.
As far as physics is concerned, you know that the total momentum is conserved, see
http://en.wikipedia.org/wiki/Momentum
There is a good illustration and formulas here http://en.wikipedia.org/wiki/Elastic_collision#Two-_and_three-dimensional
You can simplify formulas if the two object have the same weight.
so now, let's consider the reference frame in which c2 is fixed and center in (0,0).
c1 velocity in this reference would be :
c1.xfi=c1.xi-c2.xi
c1.yfi=c1.yi-c2.yi
Now you have a collision when the distance between the two is the sum of radius. Consider the tangent plane of the two circles.
You now have to decompose the velocity of c1 into a tangent component, which is conserved, and a perpendicular (following the line between c1 and c2), which is transfered to c2.
Then you need to go back to your original reference frame.
(sorry i didn't give you the exact formulas but they are on the links I provided)
If I were doing this myself, I would implement the motion using Newtons law of restitution. Essentially this is a coefficient that relates approach and separation speed of 2 particles before/after impact and it has a value that depends on the material properties of your particles.
Your analysis will essentially amount to identifying the point of impact, then breaking down the approach velocities into components that are parallel and perpendicular to the line of centres of the circle at the point of impact.
The momentum of the particles is conserved perpendicular to the line of centres (so the velocities in that direction remain unchanged by the collision) and the law of restitution applies to the velocities parallel to the line of centres. Thus if you fix the coefficient of restitution (it has to be between 0 and 1) to some value of your choice you can use this law to calculate the separation speeds along the line of centres of your particles after collision using the value of the approach speeds.
If your particles are all of the same mass and radius then the calculations become simpler. You can model elastic collisions by setting the coefficient to 1 (this indicates that separation speed of the particles is the same as the approach speed) which is probably the easiest place to start. By changing the value you will see different behaviour between particles after collisions.
Sorry not to be able to write this all down in formula for you, but this is not really the appropriate place for it. Living in the UK I have no idea what "9th grade" is so I can't assess if the above is too advanced for your current level of education. Here in the UK this type of problem would typically be covered at A-level mathematics education level.
Hopefully though it will give you an indication of the terms and topics that you can teach yourself/ research in order to achieve your goal.
I am writing a fairly simple script in JavaScript using the canvas. It draws a central node which pulls all of the surrounding nodes towards it. This works great, however I need each node to repel each other.
I am going to do this by increasing each nodes velocity away from each other so eventually they should level out and end up looking something like a flower. It needs to be enough force to stop them from hitting each other or sinking into the center node without flying off into the distance.
I just can not work out how I can have a higher number the closer they get.
So if two nodes where 10px away from each other it would add 5 in force to one of their x velocities. But if they where 1000px away from each other then it would add almost nothing to the force of one of the nodes.
Does anyone know of a mathematical equation I can use to work this kind of thing out, or maybe a nudge in the right direction?
TL;DR: Depending on how close two x values are, I need to increment the x velocity of one node so they move apart but eventually level out. It is just the maths I can not crack, I have pretty much all of the JavaScript done, including the implementation of velocity.
Thanks, and sorry it is a bit wordy.
You just need an inverse (or inverse square) relationship:
var increment = k / distance;
or:
var increment = k / (distance * distance);
You can determine k based on the actual values you want, for example, in the first case, if you wanted an increment of 5 for a distance of 10, you would set k = increment * distance = 50.
Look into the equations governing electrical point charges, have the velocity be based on the "force" each "charge" would feel based on its proximity.
I'm looking to create a basic Javascript implementation of a projectile that follows a parabolic arc (or something close to one) to arrive at a specific point. I'm not particularly well versed when it comes to complex mathematics and have spent days reading material on the problem. Unfortunately, seeing mathematical solutions is fairly useless to me. I'm ideally looking for pseudo code (or even existing example code) to try to get my head around it. Everything I find seems to only offer partial solutions to the problem.
In practical terms, I'm looking to simulate the flight of an arrow from one location (the location of the bow) to another. I have already simulated the effects of gravity on my projectile by updating its velocity at each logic interval. What I'm now looking to figure out is exactly how I figure out the correct trajectory/angle to fire my arrow at in order to reach my target in the shortest time possible.
Any help would be greatly appreciated.
Pointy's answer is a good summary of how to simulate the movement of an object given an initial trajectory (where a trajectory is considered to be a direction, and a speed, or in combination a vector).
However you've said in the question (if I've read you correctly) that you want to determine the initial trajectory knowing only the point of origin O and the intended point of target P.
The bad news is that in practise for any particular P there's an infinite number of parabolic trajectories that will get you there from O. The angle and speed are interdependent.
If we translate everything so that O is at the origin (i.e. [0, 0]) then:
T_x = P_x - O_x // the X distance to travel
T_y = P_y - O_y // the Y distance to travel
s_x = speed * cos(angle) // the X speed
s_y = speed * sin(angle) // the Y speed
Then the position (x, y) at any point in time (t) is:
x = s_x * t
y = s_y * t - 0.5 * g * (t ^ 2)
so at impact you've got
T_x = s_x * t
T_y = -0.5 * g * (t ^ 2) + s_y * t
but you have three unknowns (t, s_x and s_y) and two simultaneous equations. If you fix one of those, that should be sufficient to solve the equations.
FWIW, fixing s_x or s_y is equivalent to fixing either speed or angle, that bit is just simple trigonometry.
Some combinations are of course impossible - if the speed is too low or the angle too high the projectile will hit the ground before reaching the target.
NB: this assumes that position is evaluated continuously. It doesn't quite match what happens when time passes in discrete increments, per Pointy's answer and your own description of how you're simulating motion. If you recalculate the position sufficiently frequently (i.e. 10s of times per second) it should be sufficiently accurate, though.
I'm not a physicist so all I can do is tell you an approach based on really simple process.
Your "arrow" has an "x" and "y" coordinate, and "vx" and "vy" velocities. The initial position of the arrow is the initial "x" and "y". The initial "vx" is the horizontal speed of the arrow, and the initial "vy" is the vertical speed (well velocity really but those are just words). The values of those two, conceptually, depend on the angle your bowman will use when shooting the arrow off.
You're going to be simulating the progression of time with discrete computations at discrete time intervals. You don't have to worry about the equations for "smooth" trajectory arcs. Thus, you'll run a timer and compute updated positions every 100 milliseconds (or whatever interval you want).
At each time interval, you're going to add "vx" to "x" and "vy" to "y". (Thus, note that the initial choice of "vx" and "vy" is bound up with your choice of time interval.) You'll also update "vx" and "vy" to reflect the effect of gravity and (if you feel like it) wind. If "vx" doesn't change, you're basically simulating shooting an arrow on the moon :-) But "vy" will change because of gravity. That change should be a constant amount subtracted on each time interval. Call that "delta vy", and you'll have to tinker with things to get the values right based on the effect you want. (Math-wise, "vy" is like the "y" component of the first derivative, and the "delta vy" value is the second derivative.)
Because you're adding a small amount to "vy" every time, the incremental change will add up, correctly simulating "gravity's rainbow" as your arrow moves across the screen.
Now a nuance you'll need to work out is the sign of "vy". The initial sign of "vy" should be the opposite of "delta vy". Which should be positive and which should be negative depends on how the coordinate grid relates to the screen.
edit — See #Alnitak's answer for something actually germane to your question.