Skip to main content
Participant
March 23, 2022
Question

autonomously moving movieclip

  • March 23, 2022
  • 1 reply
  • 190 views

I'm making an HTML5 document with javascript - and I'm not the best coder.  I want to include code in a movieclip that will make it move randomly around the stage, separate from what is going on in my main timeline.  I've done this before in Edge Animate (see this) but the same code doesn't work.  What I've tried so far is to open the timeline of the Movieclip and add this code in Actions:

 

var randX; //new position
var randY;
var timeX;
var oldX = 0; //starting position
var oldY = 0;


//chooses a new posiiton to go randomly
function randomNumbersX (){
randX = Math.floor(Math.random()*589);//scaled to the size of the screen
randY = Math.floor(Math.random()*120);
constantSpeedX();
moveMeX();
}
randomNumbersX();

//scales time factor so the speed is the same no matter the distance moved
function constantSpeedX (){
var left = oldX;
var top = oldY;
var a = left - randX;
var b = top - randY;
var c = Math.floor(Math.sqrt((a*a)+(b*b)));
var percentOf = c/600;
timeX = Math.floor(2000 * percentOf);
}

// move the object to the new position
function moveMeX()
{ this.animate([{transform: 'translate(oldX,oldY)'},{transform: 'translate(randX,randY)'}],
{duration: timeX});
oldXX = randXX;
oldYX = randYX;
}

 

Help!!!!

This topic has been closed for replies.

1 reply

kglad
Community Expert
Community Expert
March 26, 2022

there's not animate() method, so you'll need to encode that.

SlishdfAuthor
Participant
March 28, 2022
Yes - that's my question. What is the Javascript code for going from x, y
to a new x, y in Z seconds?
kglad
Community Expert
Community Expert
March 28, 2022

// this.move_mc is the movieclip moving within stageW and stageH

this.stageW = 800;
this.stageH = 600;
this.speed = 3;

if(!this.alreadyStarted){
this.alreadyStarted = true;
randomNumbersF.bind(this)();
createjs.Ticker.addEventListener("tick",updateF.bind(this));
}
function randomNumbersF(){
this.randX = Math.floor(Math.random()*this.stageW);//scaled to the size of the screen
this.randY = Math.floor(Math.random()*this.stageH);
this.r = Math.sqrt( (this.move_mc.y-this.randY)*(this.move_mc.y-this.randY) + (this.move_mc.x-this.randX)*(this.move_mc.x-this.randX) );
linearEqF.bind(this)();
}
function linearEqF(){
this.inc = 1;
this.theta = Math.atan2( this.randY-this.move_mc.y, this.randX-this.move_mc.x );
}

function updateF(){
this.move_mc.x += this.speed*Math.cos(this.theta);
this.move_mc.y += this.speed*Math.sin(this.theta);
if(this.inc*this.speed >= this.r){
randomNumbersF.bind(this)();
}
this.inc++;
}