Can't stop the particles from overshooting - actionscript-3

I am trying to create a simple particle simulation. There are two types of particles static and moving. Static particles attract moving particles towards their centre. Static particles have a strength attribute which dictates how hard they are pulling the moving particles
var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x);
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y));
moving.velX += Math.cos(angle + Math.PI) * static.strength / dist;
moving.velY += Math.sin(angle + Math.PI) * static.strength / dist;
The problem is a when a particle is just passing through the centre the distance is very small that results in very large velocity values.
I added an extra check for distance before calculating velocity.
if (dist < 1)
dist = 1;
But the problem still persists. I cant figure out the problem.
Here is a snapshot of an overshoot happening.

You are probably declaring that dist value before running the dist calculation or after running the vel calculation. Instead, make sure that the dist check you are doing is between the dist calculation and the vel calculation. Vesper is correct as well, in that to get the correct force effect, it should use the distance squared. But even doing that, you can still get undesirable (although completely accurate, mathematically) results.
var angle:Number = Math.atan2(moving.y - static.y , moving.x - static.x);
var dist = Point.distance(new Point(moving.x,moving.y) , new Point(static.x,static.y));
if (dist < 1) dist = 1; // just make sure your constraint goes here.
moving.velX += Math.cos(angle + Math.PI) * static.strength / dist / dist; // this uses dist squared
moving.velY += Math.sin(angle + Math.PI) * static.strength / dist / dist; // but don't use this method in addition to Vesper's or you'll have dist to the power of 4.

Normal force fields use square of distance as modifier, you here use single power of distance, of course the force field performs differently. You should change the var dist line to the following:
var dist:Number = (moving.x-static.x)*(moving.x-static.x) + (moving.y-static.y)*(moving.y-static.y);
This way dist will hold square of actual distance, so dividing by dist would give you the proper force field configuration.
And, please rename static, as it's a reserved word in AS3.

Related

AS3:Move Objects in a curve path using as3 programming?

I need to move many objects in a curve path across screen randomly. The objects start path and towards path also should take randomly. I had searched on google and finally i found one usefull tutorial to draw a curve. But i don't know how to move the objects using that curve path. But i am sure there would be some formula in as3 which has to use sin and cos theta. So please let me know if anybody have a solution for my problem. And also if i got any sample projects also would be very usefull for me.
And the link which i got to draw curve is as follows.
http://active.tutsplus.com/tutorials/actionscript/the-math-and-actionscript-of-curves-drawing-quadratic-and-cubic-curves/?search_index=4.
Thanks in advance.Immediate Help would be appreciated.
A quick'n'dirty would be using polar to cartesian coordinates(sin and cos) as you mentioned:
import flash.events.Event;
var a:Number = 0;//angle
var ra:Number = .01;//random angle increment
var rx:Number = 100;//random trajectory width
var ry:Number = 100;//random trajectory height
graphics.lineStyle(1);
addEventListener(Event.ENTER_FRAME,function (event:Event):void{
a += ra;//increment angle
rx += a;//fidle with radii otherwise it's gonna be a circle
ry += a;//feel free to play with these
graphics.lineTo(225 + (Math.cos(a) * rx),//offset(225,200)
200 + (Math.sin(a) * ry));//and use pol to car conversion
if(a > Math.PI) reset();//reset at 180 or any angle you like
});
function reset():void{
trace('reset');//more values to tweak here
a = Math.random();
ra = Math.random() * .0001;
rx = 20 + Math.random() * 200;
ry = 20 + Math.random() * 200;
}
Random numbers need tweaking to get mostly rounder ellipses (rather than flatter ones), but the principle is the same.
If you don't mind using libraries, why not try TweenLite's BezierPlugin or BezierThroughPlugin. Should be easy to randomize start/end points.
Also you can check out the first part of this older answer on quadratic,cubic and hermite interpolation
In my example I'm drawing a path, but of course, you could use those computed x,y coordinates to plug into a DisplayObject to move it on screen.

AS3: diagonal movement

I'm programming a flash game, I made an array of points (x and y positions) that some movieclips must follow. Those movieclips have a certain speed (they make steps of 5 pixels for now). When I want to move them horizontally or vertically, everything's fine, I have to add or remove 5 pixels of those clips' x or y. But sometimes they have to move diagonally and now that's complicated.
What I'm doing:
var angle:Number = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x) * 180 / Math.PI;
var xstep:Number = Math.cos(angle) * this.speed;
var ystep:Number = Math.sqrt(Math.pow(this.speed, 2) - Math.pow(xstep, 2));
this.x += xstep;
this.y += ystep;
It's only a fraction of the code, but I think it's all you need.
Basically, this makes my movieclip do a little step (of this.speed (currently set to 5) pixels).
If the current point and the next point have the same y position, it works fine. When they don't, it doesn't work. The angle is right at first but it slowly decreases (while it should stay the same). I don't know if it's the angle that isn't computed the right way or if it's the x and y steps, but it's one of those, I'm sure.
Try this instead:
var angle:Number = Math.atan2(nextPoint.y - this.y, nextPoint.x - this.x);
var xstep:Number = Math.cos(angle) * this.speed;
var ystep:Number = Math.sin(angle) * this.speed;
Because cos operates on angles in radians, you don't need to convert to degrees. Computing the y component of an angle uses sin, so it should be similar to x. I'm not able to test this, but it's possible that ystep will be backwards and may need to be multiplied by -1.

Bezier Curve always the same length

I'm working on a game in HTML5 canvas.
I want is draw an S-shaped cubic bezier curve between two points, but I'm looking for a way to calculate the coordinates of the control points so that the curve itself is always the same length no matter how close those points are, until it reaches the point where the curve becomes a straight line.
This is solvable numerically. I assume you have a cubic bezier with 4 control points.
at each step you have the first (P0) and last (P3) points, and you want to calculate P1 and P2 such that the total length is constant.
Adding this constraint removes one degree of freedom so we have 1 left (started with 4, determined the end points (-2) and the constant length is another -1). So you need to decide about that.
The bezier curve is a polynomial defined between 0 and 1, you need to integrate on the square root of the sum of elements (2d?). for a cubic bezier, this means a sqrt of a 6 degree polynomial, which wolfram doesn't know how to solve. But if you have all your other control points known (or known up to a dependency on some other constraint) you can have a save table of precalculated values for that constraint.
Is it really necessary that the curve is a bezier curve? Fitting two circular arcs whose total length is constant is much easier. And you will always get an S-shape.
Fitting of two circular arcs:
Let D be the euclidean distance between the endpoints. Let C be the constant length that we want. I got the following expression for b (drawn in the image):
b = sqrt(D*sin(C/4)/4 - (D^2)/16)
I haven't checked if it is correct so if someone gets something different, leave a comment.
EDIT: You should consider the negative solution too that I obtain when solving the equation and check which one is correct.
b = -sqrt(D*sin(C/4)/4 - (D^2)/16)
Here's a working example in SVG that's close to correct:
http://phrogz.net/svg/constant-length-bezier.xhtml
I experimentally determined that when the endpoints are on top of one another the handles should be
desiredLength × cos(30°)
away from the handles; and (of course) when the end points are at their greatest distance the handles should be on top of one another. Plotting all ideal points looks sort of like an ellipse:
The blue line is the actual ideal equation, while the red line above is an ellipse approximating the ideal. Using the equation for the ellipse (as my example above does) allows the line to get about 9% too long in the middle.
Here's the relevant JavaScript code:
// M is the MoveTo command in SVG (the first point on the path)
// C is the CurveTo command in SVG:
// C.x is the end point of the path
// C.x1 is the first control point
// C.x2 is the second control point
function makeFixedLengthSCurve(path,length){
var dx = C.x - M.x, dy = C.y - M.y;
var len = Math.sqrt(dx*dx+dy*dy);
var angle = Math.atan2(dy,dx);
if (len >= length){
C.x = M.x + 100 * Math.cos(angle);
C.y = M.y + 100 * Math.sin(angle);
C.x1 = M.x; C.y1 = M.y;
C.x2 = C.x; C.y2 = C.y;
}else{
// Ellipse of major axis length and minor axis length*cos(30°)
var a = length, b = length*Math.cos(30*Math.PI/180);
var handleDistance = Math.sqrt( b*b * ( 1 - len*len / (a*a) ) );
C.x1 = M.x + handleDistance * Math.sin(angle);
C.y1 = M.y - handleDistance * Math.cos(angle);
C.x2 = C.x - handleDistance * Math.sin(angle);
C.y2 = C.y + handleDistance * Math.cos(angle);
}
}

AS3 Continuous value from rotation slider

I have a dial which I drag around a circle to give me a reading between 0 and 1.
Something like this:
dx = mouseX-centerX;
dy = mouseY-centerY;
rad = Math.atan2(dy,dx);
rad += offset;
Tweener.addTween(knob,{y:centerY - Math.cos(rad)*radius, time:.1, transition:"easeOutSine"});
Tweener.addTween(knob,{x:centerX + Math.sin(rad)*radius, time:.1, transition:"easeOutSine"});
knob.rotation = rad * 180 / Math.PI;
This work's great, except when the slider goes from 359 degrees to 1 degree, my value between 0 and 1 returns to zero. (Which makes sense, as the value is based on the angle of my slider)
I'm trying to find a way for the dial to move from 359 degrees to 361 and onwards basically.
In my head: I need to check if the next value of my mouse drag goes past the 360 degree point and add 360 to the total, to stop it returning to zero and continue to 361 degrees.
I just cant work out how to put this into code...
On each frame when you are rotating the knob, check the change in angular distance instead of direct angle.
Save the previous frames angle and see if the difference is positive or negative.
var rad = Math.atan2(dy, dx);
var diff = rad - oldRad;
oldRad = rad;
if( diff > Math.PI )
diff -= Math.PI * 2;
if( shortestAngle < -Math.PI )
diff += Math.PI * 2;
diff should contain a value that if it's been rotated to the right, is positive (or negative if rotated left). Simply add that to the total angle.
There might be some errors in the code (took it from an old project), but that's the gist of it :)
Hope that helps!

Drawing an arrow at the end point of the line using line slope

I am developing a white board application which allows the user to draw line with arrow head (some like Microsoft Word line with arrow feature). I am using graphics property along with lineTo() method to draw a line. Now i have to draw a angular arrow on the last point of line. I am drawing the arrow by connecting the points around last points. As 360 line can pass through this point and each line can have a different angle of arrow. Please suggest me the way to calculating these point around the last point.
I've been doing something myself, and I needed it to look a bit nicer than just a triangle, and use relatively inexpensive calculations (as few calls to other functions as possible, like Math trigonometry). Here it is:
public static function DrawArrow(ax:int, ay:int, bx:int, by:int):void
{
// a is beginning, b is the arrow tip.
var abx:int, aby:int, ab:int, cx:Number, cy:Number, dx:Number, dy:Number, ex:Number, ey:Number, fx:Number, fy:Number;
var size:Number = 8, ratio:Number = 2, fullness1:Number = 2, fullness2:Number = 3; // these can be adjusted as needed
abx = bx - ax;
aby = by - ay;
ab = Math.sqrt(abx * abx + aby * aby);
cx = bx - size * abx / ab;
cy = by - size * aby / ab;
dx = cx + (by - cy) / ratio;
dy = cy + (cx - bx) / ratio;
ex = cx - (by - cy) / ratio;
ey = cy - (cx - bx) / ratio;
fx = (fullness1 * cx + bx) / fullness2;
fy = (fullness1 * cy + by) / fullness2;
// draw lines and apply fill: a -> b -> d -> f -> e -> b
// replace "sprite" with the name of your sprite
sprite.graphics.clear();
sprite.graphics.beginFill(0xffffff);
sprite.graphics.lineStyle(1, 0xffffff);
sprite.graphics.moveTo(ax, ay);
sprite.graphics.lineTo(bx, by);
sprite.graphics.lineTo(dx, dy);
sprite.graphics.lineTo(fx, fy);
sprite.graphics.lineTo(ex, ey);
sprite.graphics.lineTo(bx, by);
sprite.graphics.endFill();
}
You can also add the line color and thickness to the argument list, and maybe make it a member function of an extended Sprite, and you have a pretty nice, versatile function :) You can also play a bit with the numbers to get different shapes and sizes (small changes of fullness cause crazy changes in look, so careful :)). Just be careful not to set ratio or fullness2 to zero!
If you store the start and end point of the line, adding the arrow head should be relatively simple. If you subtract the end point coordinates from the start point coordinates, you will get the arrow direction vector (let's call it D). With this vector, you can determine any point on the line between the two points.
So, to draw the arrow head, you would need to determine a point (P1) on the segment that has a specific distance (d1) from the end point, determine a line that passes through it, and is perpendicular to D. And finally get a point (P2) that has a distance (d2) from the previously determined point. You can then determine the point that is symmetrical to P2, relative to D.
You will thus have an arrow head the length of d1 and a base with of 2 * d2.
Some additional information and a few code examples here: http://forums.devx.com/archive/index.php/t-74981.html