开发者

How to calculate third point on line using atan2?

I'm trying to animate some bitmaps out in relation to a center point. They don't all start at that center point, but I want them to fly out as though a force from that center point slammed into them and pushed them outwards radially, such that they fly completely off the stage.

So: I know the center point, and the x and y position of each bitmap arranged around it. For each one I can draw a line from the center to that x,y point. I should then be able to get the angle formed by that line to the horizontal, and then set a destination point farther out on that line. The bitmap will be tweened out to that point. I believe that that is what Math.atan2 is for.

Here's what I've got as I iterate through the array of bitmaps (i is an object):

var angle:Number = Math.atan2(i.bitmap.y - centerY, i.bitmap.x - centerX) * 180 / Math.PI;
var dist:Number = 200;              //arbitrary number, just to test
 destX = centerX  + dist * Math.cos(angle);  //destination x
 destY = centerY  + dist * Math.sin(angle);  //destination y

Instead of th开发者_开发百科ese things gliding out radially, they're jumping around.

I'm having trouble understanding atan2 and exactly what I'm doing wrong.

Thanks,

David


You can achieve the same effect without trigonometric functions using just vector operations:

var dist:Number = 200;              //arbitrary number, just to test
var dx:Number = i.bitmap.x - centerX;
var dy:Number = i.bitmap.y - centerY;
var length:Number = Math.sqrt( dx*dx + dy*dy );
var normalizeddx:Number = dx / length;
var normalizeddy:Number = dy / length;
 destX = centerX  + dist * normalizeddx;  //destination x
 destY = centerY  + dist * normalizeddy;  //destination y

This should be much faster, than using trigonometric functions. I don't know the language specifics of actionscript, so probably this can be optimized more.


Try removing the *180/PI to keep the angle in radians.

var angle:Number = Math.atan2(i.bitmap.y-centerY, i.bitmap.x - centerX);

Then change destX and destY to

destX = i.bitmap.x  + dist * Math.cos(angle);
destY = i.bitmap.y  + dist * Math.sin(angle);


atan2 could work in this situation I suppose but I would just use atan:

var angle:Number = Math.atan((i.bitmap.y - centerY) / (i.bitmap.x - centerX));

ADDITION:

Code I just saw on another forum that appears to do what you want (there's only a slight difference from what you wrote in the first place)

var angle:Number = Math.atan2(mouseX,mouseY-180)-Math.PI/2;
var xNew:Number = 20*Math.cos(angle);
var yNew:Number = -20*Math.sin(angle);


You have to get rid of the *180/Math.PI part. The angle has to be in radians. So the first line would look like
var angle:Number = Math.atan2(i.bitmap.y - centerY, i.bitmap.x - centerX); The rest should be fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜