actionscript-3projectileflixel

How to make projectile motion in flixel + as3


So I have my character, who when I press the mouse button, should fire off a few lasers, to take out those bad guys.

Currently I add my little laser. Then I use this:

        this.velocity.x = (MousePos.x - StartPos.x) * bulletSpeed
        //same for Y

(I have also tried this)

        this.x += (MousePos.x - StartPos.x) / bulletSpeed
        //same for Y

Now this is would be great except for the fact that the laser doesnt move at the same pace. What I mean by this is that if the mouse is, lets say, 1000 pixels away, or 500 pixels away, it will arrive in the same amount of time, which means it goes faster if the mouse is farther away.

What I need to know, is how to make it so that the object will move at a specific speed, no matter how far it needs to go.

Thanks,


Solution

  • This is pure math. Velocity on either axis cannot be greater than BulletSpeed so anything you calculate should be like this:

    velocity.x = BulletSpeed * t;
    

    where t is a number between -1 and 1 inclusively. Moreover, this number is generally different for x and y.

    velocity.x = BulletSpeed * tx;
    velocity.y = BulletSpeed * ty;
    

    Now, comes the main part - how do you calculate the value of tx, ty? First, get the dx, dy, and the distance from StartPos to MousePos.

    var dx:Number = MousePos.x - StartPos.x;
    var dy:Number = MousePos.y - StartPos.y;
    var dist:Number = Math.sqrt(dx * dx + dy * dy);
    

    It's easy to see that while the object goes the dist distance, its x and y coordinates also go by dx and dy distances. It is happening within the same time but the dx and dy are generally different so the coords must change by different steps in order to arrive to the finish simultaneously.

    var step_x:Number = dx / dist;
    var step_y:Number = dy / dist;
    

    These values will always be between -1 and 1. Now all you need is to apply the BulletSpeed:

    velocity.x = BulletSpeed * step_x;
    velocity.y = BulletSpeed * step_y;
    

    or, now without simplifications

    velocity.x = BulletSpeed * dx / dist;
    velocity.y = BulletSpeed * dy / dist;