HI i am trying to to the above. I have two items on a stage and i only want them to move with in a certine area and bounce off each other when they meet. I found a good random movement code on this site but now im stuck…here is what i have:
onClipEvent (load) {
//data you may want to change
width = 425;
height = 325;
speed = Math.round(Math.random()*2)+ 2;
//initial positions
x = this._x=Math.random()*width;
y = this._y=Math.random()*height;
x_new = Math.random()*width;
y_new = Math.random()height;
}
onClipEvent (enterFrame) {
//x movement
if (x_new>this._x) {
sign_x = 1;
} else {
sign_x = -1;
}
dx = Math.abs(x_new-this._x);
if ((dx>speed) || (dx<-speed)) {
this._x += sign_xspeed;
} else {
x_new = Math.random()width;
}
//y movement
if (y_new>this._y) {
sign_y = 1;
} else {
sign_y = -1;
}
dy = Math.abs(y_new-this._y);
if ((dy>speed) || (dy<-speed)) {
this._y += sign_yspeed;
} else {
y_new = Math.random()*height;
}
}
Thanks in advance for your help.
attach this code in your movie:
//collision detection
for (var i = 0; i<3; i++) {
if (this == _root[“ball”+i]) {
continue;
}
if (this.hitTest(_root[“ball”+i])) {
if (x_new>this._x) {
x_new = this._x-(x_new-this._x);
} else {
x_new = this._x+(this._x-x_new);
}
if (y_new>this._y) {
y_new = this._y-(y_new-this._y);
} else {
y_new = this._y+(this._y+y_new);
}
}
}
//border detection
if (this._x>width || this._x<0) {
x_new = Math.random()*width;
}
if (this._y>height || this._y<0) {
y_new = Math.random()*height;
}
I pasted the code you provided into each of the movie clips and i recieved an error. From the error it seems that the code needed to be in the onclip event. I put it there and i didnt get the error anymore but it still doesnt seem to be working. From your code it appears that the movie clips need to be named ball1 and ball 2 correct? also the fla you included i couldnt open. I am using version MX 8
Idealy i would like to not use the code i provided. I would like to have 4 walls (wall1, wall2, wall3, wall4 and two moving clips (frame1 and fram2) and have the two frames bounce around off the walls and each other.
again thanks in advance for your help.
As for your error, that is because the code has to be in your onEnterFrame clip event.
I think one problem with your idea is that you want to generate random motion but have the balls bounce off each other realistically I:-)
If you want a realistic effect why not make the direction they are headed when loaded random but any direction change after that to be based on the interactions between the walls + other balls on screen? I think this might be more of what you are looking for.