1

I'd like to move an AS 3 movieclip randomly. This is what I currently have, bound to the ENTER_FRAME event. This obviously moves the movieclip from the left upper to the right lower edge, so I need some kind of switch to add/substract the target positions.

function movePsycho(e:Event):void {
    e.target.y += Math.random()*2;
    e.target.x += Math.random()*2;
    if (e.target.y >= stage.height || e.target.x >= stage.width)
        e.target.removeEventListener(Event.ENTER_FRAME, movePsycho);
}
0

2 Answers 2

1

You don't need add/substract thing. You just have to make sure not only you get positive values out of your random, but negatives too, so it runs to all sides.

Try changing your random generating lines to this:

e.target.y += Math.random()*10 - 5;
e.target.x += Math.random()*10 - 5;

This will work if you want to make it move in a 5px radius.

I just realized you may want to generate a new random point on the screen, then move to that point and when your object reaches the destination generate another random point to go to. So if that's the case, try this:

mc.addEventListener(Event.ENTER_FRAME, onFrame);

var dirX:int = mc.x;
var dirY:int = mc.y;

function generateRandomPoint():void
{
    dirX = Math.random() * stage.stageWidth;
    dirY = Math.random() * stage.stageHeight;
}

function onFrame(e:Event):void
{
    mc.x += (dirX - mc.x) * 0.1;
    mc.y += (dirY - mc.y) * 0.1;

    if(Math.abs(dirX - mc.x) < 1 || Math.abs(dirY - mc.y) < 1)
        generateRandomPoint();
}
Sign up to request clarification or add additional context in comments.

Comments

1

i don't know actionscript but you may find help with this

http://www.actionscript.org/forums/showthread.php3?t=270725

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.