sine wave drawing using JavaScript - javascript

I am working on creating a simple snow simulation, but I am failing horribly on the math. Basically, when a snowflake is initialized, it's x position is set randomly somewhere on the svg canvas. Then from there, it falls straight down. It should be simulating a sine wave (the x coordinates should move like a sine wave).
I haven't done trig since last year so i'm a bit rusty. Math.sin() takes radians I believe, so I multiply by 180, then divide by pi to convert to degrees?
Assume x is the current x position of a snowflake, and width is the width of the canvas.
x += (Math.sin(((x/width)*(180/Math.PI)))*width)
It kind of works, but it is all over the place. I have a vague idea of what i'm doing, but I can't seem to push the math from my brain to code.
Here's a JSFiddle:
What am I doing incorrectly?

It should be:
x += A*Math.sin(F*(y/Height)*2*Math.PI);
where A is the amplitude, i.e. how many pixels you want the flake to shift left and right (note that total shift will be 2*A). F is the frequency, or how often you want the flake to shift left and right (I'd set it at random between 2 and 10 for each flake).

Related

How can I predict the stopping angle of a spinning wheel?

I'm trying to predict the angle in which a spinning wheel will stop if it is slowed down to a rotational speed of 0 over a certain time.
For example;
If my wheel is spinning at +20 degrees per tick, and it reaches a set angle of say, 720 degrees, where I then begin to slow it down to a stop over 5 seconds, what angle will it rest at.
I have been looking at a lot of existing questions and material for this and am aware of the sort of maths I need to be working with; getting the deceleration speed and rotational velocity, but I'm struggling to use this information to predict an end angle.
This was a particularly useful resource but I am still unsure on how to translate this math into a predicted resting angle.
https://physics.stackexchange.com/questions/142761/how-to-model-a-very-simple-spinning-wheel
Thanks in advance.
The answer depends on the mechanism that stops it, but if we assume that it's simple friction, then deceleration is constant and the answer is easy:
If it starts off at 20 degrees per tick, then the average speed during the slowdown period is 10 degrees per tick, so 720 + 10 * 5 * ticks_per_second degrees.
Assuming constant deceleration (dry friction), the angular speed decreases linearly. Hence, the average speed is the half* of the initial speed, or
A / T = Ω / 2
where A is the traversed angle, T the time to stop and Ω the initial angular speed.
Hence
A = T Ω / 2
*For the same reason that the area of a right triangle is the half of the area of the bounding rectangle.

Animating along a curve using Javascript & simple math

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.

Procedural terrain generation with blocks

I am using three.js to create procedurally generated terrain using Perlin Noise.
I am creating the terrain using a series of blocks, but their heights along their borders are not corresponding to one another as you can see below.
How should I approach matching the height maps across blocks?
I'm using Perlin Noise Algorithm for generating heights; the problem is that the height of each point is indipendent from the heights of the near points. I've other noise algorithm, but i have the same problem..
There's a really good video on infinite terrain here: https://www.youtube.com/watch?v=IKB1hWWedMk
It's in processing, but the same concept can be applied to whichever noise library you're using - I'm going to assume that you're using Perlin noise. In which case, you need to look at the values you're passing into this function and change them based on how big your blocks are.
For example, imagine a 3x3 grid of blocks. If your middle block is (x, y), and each block is 10x10 units in size, if you move 'north' (for lack of a better term), you'd need to be getting (x, y - 10) from your noise function.
The video explains it way better than I can, but hopefully this has helped. Without more knowledge of the function you're using I can't really give a more detailed answer.
This answer will explain how to solve it for a single axis, x. It is then trivial to do the same for the y (z in three.js) axis.
The first step is to ensure the perlin noise is using the same random seed for each block. This will ensure that blocks share the same perlin noise map and so can transition smoothly between them.
The second part is to have a mapping between your block units and what is passed into the perlin noise function. For example your block x may be going from -512 to 512 units, so you get a height value for each x vertex by passing in -0.5 to 0.5 for each x vertex into the noise function.
E.g.
vertextHeight = perlin(vertexX / 1024, vertextY / 1024)
Your second block will then be offset so its edge interfaces with the first block. E.g. its x position will be +1024 more than the first block, and so will go from 512 to 1536.
So in this sense, block0 will have an x offset of 0, and block1 will have an x offset of 1024. 1024 being the block width/size in three.js units.
Finally, you need to give the same offsets to the noise function, but scaled based on the mapping described above. In this example, 512 would become 0.5 and 1536 would become 1.5 which looks like this:
size = 1024;
vertextHeight = perlin((vertexX + offsetX) / size, (vertextY + offsetY) / size)`
Therefore, the x value given to the noise function at the edge between block0 and block 1 will be the same, and so will return the same height value.

JavaScript Vector2d Math

I've recently started programming small canvas games in JavaScript and is trying to wrap my head around Vector 2d math. I understand the very basics of Vectors (like they represent a point in a 2d space with a direction and that you can add, multiply, subtract and rotate them) but I don't understand how to apply vectors when for instance calculating direction and speed of an in-game object.
Check out this game:
http://rem.im/asteroid.html
A great example of a mini game driven by 2d vector math.
The great Seb Lee Delisle is using this JavaScript pseudo class for his vector calculations:
https://github.com/sebleedelisle/JSTouchController/blob/master/js/Vector2.js
I've read some tutorials on vector math but they have a 100% pure mathematical focus and don't describe how to build games with vectors like controlling space ships and bullets.
Can you point me to some tutorials of how to apply vector math in JavaScript games?
Thanks!
You can see the position of an element as a vector (x,y) which also defines a direction going from the coordinate origin (0,0) to this point.
Velocity is the rate of position change per time unit. So for example (1,5) means that with every time unit (let's say per frame) the x coordinate will change by +1 and the y coordinate will change by +5. So the new position will be (x,y)+(1,5) = (x+1, y+5)
Acceleration is the rate of velocity change per time unit. Let's say you have an acceleration of (1,1), then the velocity will change by +1 in x direction and by +1 in y direction.
Example: Current position of your object is (100, 200), its current velocity is (5,0) and the acceleration is (1,1).
Position in frame 0: (100,200), velocity (5,0)
Position in frame 1: (100,200) + (5,0) = (105,200), new velocity (5,0) + (1,1) = (6,1)
Position in frame 2: (105,200) + (6,1) = (111,201), new velocity (6,1) + (1,1) = (7,2)
etc.

2d parabolic projectile

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.

Categories