Calculate a trajectory for an object, when given an angle and a velocity in flash

守給你的承諾、 提交于 2019-12-06 00:18:30

You need a little bit of physics.

Initial speed must be calculated by using some criteria that you add on your own. One example is to calculate initial speed by using the distance between the mouse and the cannon, at the time the mouse is pressed. If the distance is greater the projectile will have a bigger speed, and if the distance is smaller the projectile will have smaller speed.

The you add an Event Listener with type ENTER_FRAME.

I guess it's 2 dimensional animation so you have to find the current x and y at any point in time.

Here's a little bit of code:

var TimeperFrame:Number = 1/fps //fps is not a constant, here you should add a number, a value that you previously added in fla. document properties. I usualy use 60 fps
var Time:Number = 0;

addEventListener(ENTER_FRAME, movingCannonBall);
function movingCannonBall(e:Event):void
{
   Time += TimeperFrame;
}

Now here's the equitation for trajectory of projectile.

x = xo + vxo·t

y = yo + vyo·t - 0.5·g·t^2

yo = initial height of your cannon ball

vyo = initial y velocity; vyo = vo·sin θ

t = time passed, we conrol that by upper code

g = acceleration (9,81 m/s^2) at Earth's surface

xo = initial distance for the start

vxo = initial x velocity; vxo = vo·cos θ

Now in the upper code we add these equitations and it should look like this:

var TimeperFrame:Number = 1/fps
var Time:Number = 0;
var initx: Number = cannonball.x;
var inity: Number = cannonball.y;
var initVelocity: Number = (you define initial Velocity by your criteria)
var G: Number = 9.81;

addEventListener(ENTER_FRAME, movingCannonBall);
function movingCannonBall(e:Event):void
{
   Time += TimeperFrame;
   cannonball.x = initx + Math.cos(angle) * initVelocity * Time;
   cannonball.y = inity + Math.sin(angle) * initVelocity * Time - G * Time * Time * 0.5
}

This should work. I have use this code many times and it's effiecient and also it's simple.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!