DEV Community

Cover image for Roller Coaster!  On the Canvas with ZIM
Dr Abstract
Dr Abstract

Posted on

Roller Coaster! On the Canvas with ZIM

Roller Coasters are a little tricky to code but ZIM has some treats to make it possible. First... ZIM does have physics but we are not going to use physics for this example. Instead we animate along a path. Here is the example on CodePen https://codepen.io/zimjs/pen/yLJKKwJ.

Animating on a path is easy in ZIM - we have Blob and Squiggle paths so here we use a Squiggle. The general animation looks like this:

const path = new Squiggle().center();
new Circle().addTo().animate({
  props:{path},
  time:3,
  loop:true,
  rewind:true
});
Enter fullscreen mode Exit fullscreen mode

You can drag along a path too and all sorts of things! Check out some examples at https://zimjs.com/nio - this was the mini-site for ZIM NIO (9) where we introduced a bunch of exciting path features.

A special thing we are doing in the animate is making the speed change depending on the height of the car. This makes the car slowdown higher up and speed up lower on the screen giving it a realistic effect! There are cool other effects like this you can do with ZIM animate and the EXTRA features (see the ZIM NIO examples).

  // adjust the speed from .1 to 4 
  // proportionally between y height of 270 to 450
  props:{path:path, speed:[.1,4,270,450]},
Enter fullscreen mode Exit fullscreen mode

In the Coaster example, we use a second fatter Squiggle just above the track. We then mask this with the circle so we can only see it through the circle. This makes it appear like a car is traveling along the path.

fatSquiggle.setMask(circle);
Enter fullscreen mode Exit fullscreen mode

We have made the path longer than the stage (viewable area). So we use the follow method of the Frame to move the scene to follow the car!

Frame.follow(car);
Enter fullscreen mode Exit fullscreen mode

It is so fun working with ZIM! Everybody who does loves it... come on and join us.


If you have not checked out the Canvas recently - you simply must! Here is the ZIM Dev Site and some In-depth Guides by Dr Abstract including Your Guide to Coding Creativity on the Canvas.

Top comments (0)