Jump to content

move a sprite along a curved path


owen
 Share

Recommended Posts

Hi, another newbie-ish question here.

 

I'm happy with moving sprites using tweens when the path is a straight line, but I also want to move a sprite around in curved path, like a rainbow or a U shape or possibly an oval or circle. I am struggling to understand how I can do this with a tween.  I need a simple example or two ideally.  Can anyone help?

 

thanks

Owen

Link to comment
Share on other sites

You can start with a Bezier curve function:

function cubicBezier(t, a, b, c, d) {        var t2 = t * t;    var t3 = t2 * t;    return a        + (-a * 3 + t * (3 * a - a * t)) * t      + (3 * b + t * (-6 * b + b * 3 * t)) * t       + (c * 3 - c * 3 * t) * t2 + d * t3;}

Then call that function in the game loop over a fixed period of time.

Use the function's return value to move the sprite along the curve.

 

Here's some generic code that does this to make a sprite arc - you'd need to adapt the code to work with Phaser.

//Initialize some variablesvar totalFrames = 120,  //The length, in frames, of your animation          frameCounter = 0,    startX = yourSprite.x,    startY = yourSprite.y,    endX = 225,    endY = 250;//Start the game loopgameLoop();function gameLoop() {  requestAnimationFrame(gameLoop);  //Run the animation while `frameCounter` is  //less than the `totalFrames`  if (frameCounter < totalFrames) {    //Find the normalized time value     var normalizedTime = frameCounter / totalFrames;    //Make the sprite follow a Bezier curve    yourSprite.x = cubicBezier(normalizedTime, startX, 25, 225, endX);    yourSprite.y = cubicBezier(normalizedTime, startY, 50, 50, endY);    //Add one to the frame counter    frameCounter += 1;  } //.. the rest of your game code}
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...