Reputation: 607
I am new to the Easeljs library and I am trying to make a circle shape follow the mouse. The problem I am encountering is that the circle is placed at the cursor's position immediately, but I want it to move slowly towards the location of the cursor. I have already tried the follow code.
var stage, label, circle;
function init() {
stage = new createjs.Stage("demoCanvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.addEventListener("stagemousemove",function(evt) {
circle.x = evt.stageX;
circle.y = evt.stageY;
createjs.Ticker.on("tick", tick); //parameters?
createjs.Ticker.setFPS(60);
stage.addChild(circle);
stage.update();
})
}
function tick(event, target_x, target_y) {
if(circle.x < target_x){
circle.x = circle.x + 1;
}
if(circle.y < target_y){
circle.y = circle.y + 1;
}
if(circle.x > target_x){
circle.x = circle.x - 1;
}
if(circle.y > target_y){
circle.y = circle.y - 1;
}
if(circle.y == target_y && circle.x == target_x){
circle.x = target_x;
circle.y = target_y;
}
stage.update(event); // important!!
}
But this code does not allow me to pass the target_x and the target_y variables to the tick function. Probably I am making some basic mistakes here, but I am not able to find the answer to my problem.
Upvotes: 0
Views: 450
Reputation: 275
@Pat4561
There are a few things that your code will need to achieve the animation effect that you are looking for.
What I would recommend would be to handle the animation interaction within the 'tick' event handler. Setting your shape's x/y position using stage.mouseX and stage.mouseY would be done within the tick.
For instance:
function tick(event) {
//Position circle to mouse location immediately.
circle.x = stage.mouseX;
circle.y = stage.mouseY;
...
}
Don't try to pass parameters to the 'tick', since it's an event handler and it only expects an event as a parameter.
If you are looking for the shape to animate with an easing factor you would handle it like this:
function tick(event) {
circle.x += (stage.mouseX - circle.x) / 6;
circle.y += (stage.mouseY - circle.y) / 6;
...
}
Check out this working example to see it in action
Also have a look at the many examples on the CreateJS GitHub repo
There you'll find a ton of great working examples that should get you started.
Upvotes: 1