Skip to main content
Participant
Mar 23, 2022 6:59 PM UTC
Question

autonomously moving movieclip

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 is closed to new replies. Start a new post to keep the conversation going.

3 replies

kglad
Community Expert
Community Expert
Mar 26, 2022 2:50 PM UTC

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

Translate
SlishdfAuthor
Participant
Mar 28, 2022 4:52 PM UTC
Yes - that's my question. What is the Javascript code for going from x, y
to a new x, y in Z seconds?
Translate
kglad
Community Expert
Community Expert
Mar 28, 2022 11:13 PM UTC

// 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++;
}

Translate