Movement in AS3 - actionscript-3

I am learning AS3. How can I move a symbol?
My Code
var counter:int = new int();
counter = 0;
var point:symbol1 = new symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
while (counter < 200)
{
trace(counter);
point.x += 1;
counter += 1;
}
}
}
But when I press space the symbol is to fast. How can edit the speed of the point?

You need to use an ENTER_FRAME event :
stage.addEventListener(Event.ENTER_FRAME,stageEnterFrame);
function stageEnterFrame(e:Event):void{
displayObject.x+=1
}
The displayList is updated only after code execution, that's why your object move so 'fast'.
This link may help you understand the process.

At the moment you are waiting for the user to press the space bar and then moving the symbol to the right by one pixel 200 times.
But as OXMO456 has said all 200 times that it moves to the right happen at the same time as if you had manually typed "point.x += 1;" 200 times.
if your intention is to only let it move to the right 200 times then you could replace the while statement with an if statement:
if(counter<200){
trace(counter);
point.x+=1;
counter+=1;
}
You could then change the speed it moves at by changing the number after "point.x+=".
An even better way of changing the speed would be by using a variable to make it clearer what the number does. This also makes it easier to use that number for other things, like moving in other directions at the same speed.
Here's what the finished code would look like with these changes and a bit of clean up:
var counter:int = 0; // setting this variable as you define it saves space
var speed:Number = 1; // here's the speed variable (declared as a number so you can have fractions)
var point:symbol1 = new symbol1();
addChild(point);
point.x = 75; // 25+50 is 75, one less thing for flash to work out
point.y = 75;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
if (counter < 200)
{
trace(counter);
point.x += 1;
counter += 1;
}
}
}
Does that make sense?

Do it like this:
Point.x += 0.2; instead of point.x += 1;

this event type is what you want:
' stage.addEventListener(Event.ENTER_FRAME,enterFrameHandler)'

Use tween:
import libraries:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
var myTween:Tween = new Tween(ball, "x", Strong.easeOut, ball.x, ball.x + 100, 5, true);
This code moving your object ("ball") to 100 on "x" axis in 5s.

Your while loop is making it fast, if you remove your while statement then it will work on SPACE DOWN

Welcome to the world of AS3.
Your description of your problem is a little vague, but i think i know what you what to do. You want to tween a display object (symbol1) 200 px right everytime you hit space? if so, here is how you do it:
import flash.events.KeyboardEvent;
import flash.events.Event;
var destinationX:int = 0; // this contains the point's destination x
var point:symbol1 = new symbol1(); // best practice is to name all your classes starting with upper case, like Symbol1, not symbol1
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
stage.addEventListener(Event.ENTER_FRAME, render);// run render function every frame
function move_handler(e:KeyboardEvent):void{// another best practice, when injecting a variable into a function declare what type the variable is, in this case e is a KeyboardEvent. :void when not returning any values from the function, basically all functions you make in the beginning should look like this
if (e.keyCode == Keyboard.SPACE) {
destinationX += 200;// add 200 to destinationX
}
}
function render(e:Event):void{ // runs every frame, if you set your fps to 30, then this will run 30 times a second
if(destinationX > point.x){//Check if point's destination x is more than the points current x position
point.x += 1;// add 1 to points x. you can change this if you want it to go faster
}
}

Check out the Greensock library - it will take all the onEnterFrame complexity out for you and has some great features.
Full doc and examples at http://www.greensock.com/

You need this
var counter:int = new int();
var vel = 1; //<------- Move 1 pixel by frame
counter = 0;
var point:symbol1 = new symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e) {
if (e.keyCode == Keyboard.SPACE) {
stage.addEventListener(Event.ENTER_FRAME,moveEnterFrame);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, move_handler);
}
}
function moveEnterFrame(e:Event):void{
point.x += vel;
counter ++;
if(counter >= 200){
stage.removeEventListener(Event.ENTER_FRAME,moveEnterFrame);
counter = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
}
}

ENTER_FRAME is the same of While.
stage.addEventListener(Event.ENTER_FRAME, nameFunction); //this event execute fps ones on default 24 frames for seconds
var speed:int = 5;
function nameFunction(ev:Event){
simbol.x += speed;
}

Draw anything and name it in the instance name box ..... so this well speed up and down by the space key ...... i use the frame rate
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
stage.addEventListener(Event.ENTER_FRAME,stageEnterFrame);
var fremCount:int;
var upDown:int;
function stageEnterFrame(e:Event):void{
if(fremCount<30 && upDown==0){
box.x+=1
fremCount++
}
if(fremCount==30){
upDown=1;
trace("For next : "+fremCount , upDown);
}
if(upDown==1){
box.x-=1
fremCount--;
}
if(upDown==1 && fremCount==0){
upDown=0;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown);
function myKeyDown(e:KeyboardEvent):void{
if (e.keyCode == Keyboard.SPACE){
trace("Success!"+stage.frameRate);
stage.frameRate += 5;
if (stage.frameRate>150){stage.frameRate=0;}
}
}

import flash.events.Event;
var point:MovieClip = new Symbol1();
addChild(point);
point.x = 25 + 50;
point.y = 25 + 50;
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e)
{
if (e.keyCode == Keyboard.SPACE)
{
stage.addEventListener(Event.ENTER_FRAME, moveRight);
}
}
function moveRight(evt:Event):void
{
point.x+=1;
}
I think this is exactly what you need. Firtly you create and call upon the key_down function. Inside this function you want to call for the move function itself. This is the function I created at the bottom. To make it stop at for example 200px I suggest to work with an if-statement and a removeEventlistener.
Please note that I changed some small codings eg "var point:MovieClip = new Symbol1(); " to make it appropriate for my symbol.

why not declare your counter variable as Number (not as int)
var counter:Number = new Number();
then change your statment as
point.x += 0.1;
counter += 0.1;
this will slow down your Point movieclip. you can change motion by changing 0.1 to any value you want.

The reason why your symbol is too fast is that your while loop iterates your point.x value 200 times in only one loop. To limit your symbol position, you must use an if statement instead of a while loop:
var point:symbol1 = new symbol1();
point.x = 75; // 25 + 50;
point.y = 75; // 25 + 50;
addChild(point);
const SPEED:Number = 0.7;
const DX:int = 200; // distance to cover
var counter:Number = 0; // counts the distance covered
stage.addEventListener(KeyboardEvent.KEY_DOWN, move_handler);
function move_handler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE && counter < DX)
{
point.x += SPEED;
counter += SPEED;
trace(counter); // stops at 200
}
}

Use the Enter Frame method.
Please don't hardcode as well :P

If you are starting you may want to consider giving one of the many existing tween engines in order to get smooth results quickly.

Related

Simple click and hit flash game

I am trying to create a simple game like whack a mole, what I want is for instead of mole make rectangle appear and disappear quickly on screen and the player has to click it more rectangles he click more his score increases.
I think it's a fairly simple game but my problem is:
How do I make the rectangles appear and disappear on screen at random position also at increasing speeds as the timer is decreasing? i.e speed of rectangles appearing and disappearing increases as the time reduces, there is a countdown time as player gets to play for 30 sec.
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
var inc:Number = 1;
var gogo:Timer = new Timer(inc*1000);
var val:Number = 30;
var counter = val;
var time2:Timer = new Timer(1000+speed);
var speed:Number = 50;
timee.text = counter;
box.addEventListener(MouseEvent.CLICK, st);
function st(event:MouseEvent):void
{
gogo.start();
time2.start();
}
gogo.addEventListener(TimerEvent.TIMER, res);
function res(ev:TimerEvent):void
{
if(counter == 0){
gogo.stop();
}else{
val = val - inc;
counter = val;
timee.text = counter;
}
}
stage.addEventListener(Event.ENTER_FRAME, yea);
function yea(e:Event):void{
speed += 50;
}
It seems to me that you need a math.random() method.
explained here
I'd personally have every successful 'hit' lower a "blinkSpeed" variable by either a set fraction of a second or a percentage and use that variable as my random input "max" number. That way it would decrease the time it could be available for automatically as they play.
Hello
Well, that wouldn't be much hard! Here's a clue.
Step1 : Create a new movieclip.
Step2 : Right click on your movie clip in the library. Click properties. Check the "Export for ActionScript" checkbox. Name the class MyEnemy (for example).
Step3 : Go to the frame and pull the Actions window.
Now put this code in it :
var mc:MyEnemy= new MyEnemy() // creates a instance of the movieclip.
addChild(mc); // adds the movie clip to the stage.
Step 4 : Now that we have added a new movieclip to the stage. To add it at a random x location in the stage, you need to make use of mc's x and y fields and the Math.random() function.
Example of Math.random() :
var randomThing:Number = Math.random() * 100 // returns a number between n, where 0 <= n < 100
Now, for example, we need both x and y values relative to the stage you must multiply Math.random() with the stage's width instead. As follows :
var randomX:Number = Math.random() * stage.stageWidth // returns a number between n, where 0 <= n < stage.stageWidth
var randomY:Number = Math.random() * stage.stageWidth // returns a number between n, where 0 <= n < stage.stageWidth
And! The magic final code would be :
mc.x = randomX;
mc.y = randomY;
Edit 1 : To add multiple "mc" movieclips to stage, we would use loops, do the follow :
stage.addEventListener(Event.ENTER_FRAME, doSimple);
function doSimple (ev:Event) {
var mc:MyEnemy = new MyEnemy();
var randomX:Number = Math.random() * stage.stageWidth // returns a number between n, where 0 <= n < stage.stageWidth
var randomY:Number = Math.random() * stage.stageWidth // returns a number between n, where 0 <= n < stage.stageWidth
for (var i:Number=1; i<=10;i++){ //i is a number, you can discard the 'i<=10' if you want an infinite loop.
addChild(mc);
}
mc.x = randomX;
mc.y = randomY;
trace("yes");
}
Conclusion : I look forward for your feedback!

How can I code an object to spawn onto the stage in the Actions panel?

I am trying to introduce a new ball into my pong game, sort of like a power up. I am writing all of my code in the Actions panel in the first frame. The new ball should appear on the stage and start moving around randomly like the original ball. Although I am using a code snippet and not .as file. So all of my code is in the Actions panel(Accessed by pressing f9).
I would also like my dynamic text box to merge with the stage colour so that you can't see the white background.
I can't show you what the fla looks like because I have less than 10 reputation, but the dynamic text box will not merge into the background and instead has a white surrounding. This hides the ball when the ball goes up.
import flash.events.Event;
import flash.ui.Mouse;
//hide mouse
Mouse.hide();
init(); //initialises everything
var bSpeedX:int = -3.5;
var bSpeedY:int = -2.5;
// assign a maximum speed to the AI
var compPaddleSpeed:int = 3.5;
var pScore:int = 0;
var cScore:int = 0;
// Updates the score
function scoreUpdate():void {
playerScore.text = ("Player Score: " + pScore);
computerScore.text = ("AI Score: " + cScore);
}
function init():void //tells flash not to return values
{
stage.addEventListener(Event.ENTER_FRAME, loop);
}
/*we want the ySpeed to be larger if there
is a greater difference between the y
positions of the ball and paddle, so I started with
(gameBallY-padY). To convert this difference
into a number between -1 and 1, I divided
this number by 25, which
is half the height of the paddle. Finally, I wanted
the ySpeed to be more powerful than
just -1 to 1, and after a bit of trial and error
I decided to times by 5 at the end
to change the total magnitude of the new ySpeed.*/
//defying the laws of Physics
function calculategameBallAngle(padY:Number, gameBallY:Number):Number
{
var ySpeed:Number = 5 * ((gameBallY-padY) / 25 );
return ySpeed;
}
//main loop
function loop(e:Event):void
{
//makes the paddle track the mouse
playerPaddle.y = mouseY;
//paddle AI
if(compPaddle.y < gameBall.y - 10){
compPaddle.y += compPaddleSpeed;//make it go up
} else if(compPaddle.y > gameBall.y + 10){
compPaddle.y -= compPaddleSpeed;//make it go down
}
//Collisions
if( playerPaddle.hitTestObject(gameBall) == true ){
if(bSpeedX < 0){
bSpeedX *= -1;
bSpeedY = calculategameBallAngle(playerPaddle.y, gameBall.y);
}
} else if(compPaddle.hitTestObject(gameBall) == true ){
if(bSpeedX > 0){
bSpeedX *= -1;
bSpeedY = calculategameBallAngle(compPaddle.y, gameBall.y);
}
}
//makes the gameBall move
gameBall.x += bSpeedX; //each frame, we add the bSpeedX to the ball's x position.
gameBall.y += bSpeedY; //same for the bSpeedY to the ball's y postion.
// checks to see if the ball misses the paddle
if(gameBall.x <= gameBall.width/2){
gameBall.x = gameBall.width/2;
bSpeedX *= -1;
cScore ++;
scoreUpdate();
//keeps the ball within the stage
} else if(gameBall.x >= stage.stageWidth-gameBall.width/2){
gameBall.x = stage.stageWidth-gameBall.width/2;
bSpeedX *= -1;
pScore ++;
scoreUpdate();
}
if(gameBall.y <= gameBall.height/2){
gameBall.y = gameBall.height/2;
bSpeedY *= -1;
}
else if(gameBall.y >= stage.stageHeight-gameBall.height/2){
gameBall.y = stage.stageHeight-gameBall.height/2;
bSpeedY *= -1;
}
//-------------------------------------------------------
//keeps the player paddle within the stage
//check if paddle is above top of the screen
if(playerPaddle.y - playerPaddle.height/2 < 0){
playerPaddle.y = playerPaddle.height/2;
} else if(playerPaddle.y + playerPaddle.hieght/2 > stage.stageHeight){
playerPaddle.y = stage.stageHeight - playerPaddle.height/2;
//check if paddle is below bottom of the screen
} else if(playerPaddle.y + playerPaddle.height/2 > stage.stageHeight){
playerPaddle.y = stage.stageHeight - playerPaddle.height/2;
}
}
If you only want your ball to be replaced with new one which has diffrent grphics and/or speed you can for example export your ball class to action script:
Library>RMB on your symbol>Properties>ActionScript Linkage>Export for ActionScript
Type your class name under Class: field like "MyBallClass" and hit OK.
Now you can construct this ball in your code and replace old one like this:
var newBall:MyBallClass = new MyBallClass();
addChild(newBall);
newBall.x = gameBall.x; newBall.y = gameBall.y;
gameBall = newBall;
Additionally you can define new variable like var speedModifier:Number = 1; to use with:
gameBall.x += bSpeedX * speedModifier;
gameBall.y += bSpeedY * speedModifier;
And change that also when you change the ball.
If You want to have multiple balls at same time You really should consider build this in OOP. For simplest example in addition to previous one
You can create MyBallClass.as file and write in it something like:
package
{
import flash.display.Sprite;
import flash.geom.Point;
public class MyBallClass extends Sprite
{
public var speedFactor:Number;
public var speed:Point = new Point(-3.5, -2.5);
public function MyBallClass(x:Number, y:Number, speedFactor:Number = 1)
{
this.x = x; this.y = y;
this.speed = speed;
}
}
}
Now you can create container for all the balls in yor game.
var balls:Vector<MyBallClass> = Vector<MyBallClass>([]);
and run your physics for all of them in a loop.
Generally main code would look something like this:
var balls:Vector.<MyBallClass> = Vector.<MyBallClass>([]);
addBall(...)//place first ball.
function loop(e:Event):void {
processBalls();
if(wantToAddNewSuperSpeedBall) addBall(x,y,3);
...
}
function processBalls() {
for (var i:int = 0; i < balls.length; i++) {
detecCollision(balls[i]);
moveBall(balls[i]);
//any code that process a single ball...
}
}
function addBall(x:Number, y:Number, speedFactor:Number = 1) {
var newBall:MyBallClass = new MyBallClass(x,y, speedFactor);
addChild(newBall);
balls.push(newBall);
}
function moveBall(ball:MyBallClass) {
ball.x += ball.speed.x * ball.speedFactor;
ball.y += ball.speed.y * ball.speedFactor;
}
So you should modify all functions which affect ball behavior to work with ball passed as argument, not only one specific instance and then use them for all balls.
There are more to cover in this topic and this isn't maybe the best approach but I've tried to make it easy to understend. There a lot of guides for OOP so you can get better idea about what is going on if you read them.
I hope that helped you somehow.

What do these statements mean and what happens when I change their values

Still learning AS3. I would love to know more about these 2 simple statements.
My educated guess is movement or gravity on the x/y co-ords?
var dx:Number = x;
var dy:Number = x;
Much appreciation!
So the code makes the character if jumping, move up at a gradually slower rate until it hits the ground again, where isJumping becomes false again. Each time the character jumps the isJumping is made true again and the cycle repeats (jumpPower is what controls how high). There is also gravity, which is also controlling how fast the jump falls.. however! I would like to point out a major flaw in this code..
jumpPower should not be controlling how fast he falls, gravity should. When jumpPower reaches zero, it then begins to fall into the negatives untill the character reaches the ground. This means that gravity + jumpPower will both be speeding the character to the ground.
I don't know if you meant to do this, but I would recommend having only gravity being the thing sending your character to the ground. A better way to code this would to give the character a velocity, which you apply to its x and y cords each enter frame.
Something like this..
velocityY += gravity;
MainChar.y += velocityY;
This way, when the character jumps, you only need to call this once:
velocityY += jumpPower;
...
Your code with velocity...
var dx:Number = x; // Not sure what these are
var dy:Number = x; // Not sure what these are
var velocityX:Number = 0;
var velocityY:Number = 0;
function doJump(evt:MouseEvent):void {
if(!isJumping) {
jumpPower = -30;
velocityY += jumpPower;
isJumping = true;
}
}
function update(evt:Event):void {
if(MainChar.y + gravity < ground) {
velocityY += gravity
MainChar.y += velocityY;
} else {
velocityY = 0;
MainChar.y = ground;
isJumping = false;
}
}
....
Final note. How come your MainChar is a static class?
I suppose the point is, not much can be answered about this question as I don't expect we have all of the code here.
On one hand you don't need to use these 2 variables dx and dy. On the contrary you forgot to declare the variables used in the code: gravity, jumpPower, isJumping and ground.
On the other hand it's better to use enterFrame event only when necessary and remove it at the end of the movement (in your function update).
At last you don't need to use your boolean variable isJumping (by actualising the value of your variable jumpPower = 30 at the end of your function update).
So your code should really be more simple:
stage.addEventListener(MouseEvent.MOUSE_DOWN, doJump);
const GRAVITY:int = 3;
var jumpPower:int = 0;
var ground:int = stage.stageHeight - MainChar.height;
function doJump(evt:MouseEvent):void {
addEventListener(Event.ENTER_FRAME, update);
}
function update(evt:Event):void {
MainChar.y -= jumpPower;
jumpPower -= 2;
MainChar.y += GRAVITY;
if(MainChar.y + GRAVITY > ground) {
MainChar.y = ground;
jumpPower = 30;
removeEventListener(Event.ENTER_FRAME, update);
}
}

Breakout with Flash: I need help to improve my Brick n Ball collision

I've been stuck on this problem for a very long time now, I've searched around alot and tried stuff, but nothing works. Some explanations are just very hard for me to understand as Im pretty new to programming overall and got alot to learn.
I have two problems
1: The ball wont collide with the bricks sometimes when the speed is too fast.
2: The ball is capable of hitting 2 bricks.
Both problems is related to the fact that 60 fps isnt enough for my type of collision detection to work properly.
I just need someone to explain in a simple way as possible what I need to do to make a collision detection that will prevent this from happen.
Here's my current collision code:
private function checkCollision(): void {
grdx = Math.floor((ball.x) / 28);
grdy = Math.floor((ball.y) / 14);
ngrdx = Math.floor((ball.x + dx) / 28);
ngrdy = Math.floor((ball.y + dy) / 14);
var flipX: Boolean = false;
var flipY: Boolean = false;
if ((grdy <= level.length - 1) &&
(ngrdy <= level.length - 1) &&
(grdy >= 0 && ngrdy >= 0)) {
if (testBlock(grdx, ngrdy)) {
flipY = true;
paddleFlag = 1;
}
if (testBlock(ngrdx, grdy)) {
flipX = true;
paddleFlag = 1;
}
if (testBlock(ngrdx, ngrdy)) {
flipX = true;
flipY = true;
paddleFlag = 1;
}
dx *= flipX ? -1 : 1;
dy *= flipY ? -1 : 1;
}
}
private function testBlock(xPos: int, yPos: int): Boolean {
if (level[yPos][xPos] > 0 && level[yPos][xPos] != 13) {
trace("hit on X,Y");
level[yPos][xPos] = 0;
breakBlock("Block_" + yPos + "_" + xPos);
trace("Block: " + totalBreaks + " / " + totalBlocks);
return true;
}
return false;
}
private function breakBlock(blockName: String): void {
if (this.getChildByName(blockName)) {
this.removeChild(this.getChildByName(blockName));
totalBreaks++;
}
}
Thank you and sorry for my bad english, its not my motherlanguage.
One solution is to move the ball in smaller iterations, multiple times in a given frame.
For example, and I am giving this solution assuming that you are moving the ball based on the time elapsed from the last frame.
Suppose that 30 milliseconds have elapsed since the last frame update. In that case you would update the movement/collision twice in that frame using 15 millisecond as your time elapsed.
The higher resolution of collision you want, the more iterations you would do.
Here's an example :
// class declarations
var lastFrame:Number;
var iterationsPerFrame:int;
function startGame():void
{
// lets specify 3 updates per frame
iterationsPerFrame = 3;
// save initial time
lastFrame = getTimer();
// create your listener
addEventListener(Event.ENTER_FRAME, update);
}
function update(e:Event):void
{
var currentFrame:Number = getTimer();
var deltaTime:Number = (currentFrame - lastFrame)/1000;
var iterationDelta:Number = deltaTime/iterationsPerFrame;
for (var index:int = 0;index < iterationsPerFrame;index++)
{
// I'm assuming dx,dy are the velocity of the ball, in pixels per second
ball.x += dx * iterationDelta;
ball.y += dy * iterationDelta;
// check collision
}
// set lastFrame to the currentFrame time, preparing for next frame
lastFrame = currentFrame;
// after this, your frame is going to render
}
You could work out how far the ball travels each frame (A) based on its speed, how far the ball is from the paddle (B) and if A > B manually trigger a collision that frame.
You're essentially checking every bricks X and Y coordinate to the balls X and Y coordinate, so if the bricks are stored in an array this becomes: Sqrt( Sqrd(p2.x - p1.x) + Sqrd(p2.y - p1.y))
for(var i=0; i<brickArray.length; i++)
{
var distance:Number = Math.sqrt((brickArray[i].x - ball.x) * (brickArray[i].x - ball.x) +
(brickArray[i].y - ball.y) * (brickArray[i].y - ball.y));
}
This is a very good tutorial on high speed collison detection:
http://www.newgrounds.com/bbs/topic/1072673

Draw random way in ActionScript

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);
}
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();
}
i don't know actionscript but you may find help with this
http://www.actionscript.org/forums/showthread.php3?t=270725