Copy link to clipboard
Copied
Hello all.
I have a simple program where two balls bounce off the four sides of the stage and off each other.
The program runs fine for about a minute, then the ball start to act erractically ; e.g. the balls start bouncing in another direction before hitting the sides. Eventually, the motion of the ball behave as if they are in a small contained space.
import flash.events.Event;
import flash.media.Sound;
var xVel:Number = 5;
var yVel:Number = 5;
ball_mc.addEventListener(Event.ENTER_FRAME, redBall);
yball.addEventListener(Event.ENTER_FRAME, yellowBall);
function redBall(evtObj:Event):void
{
ball_mc.x += xVel;
ball_mc.y += yVel;
if (ball_mc.y > stage.stageHeight)
{
yVel *= -1;
}
if (ball_mc.y < 0)
{
xVel *= -1;
}
if (ball_mc.x < stage.stageWidth)
{
xVel *= -1;
}
if (ball_mc.x < 0)
{
xVel *= -1;
}
if (ball_mc.hitTestObject(yball))
{
trace("hit");
xVel *= -1;
}
}
function yellowBall(evtObj:Event):void
{
yball.x += xVel;
yball.y += yVel;
if (yball.y > stage.stageHeight)
{
yVel *= -1;
}
if (yball.y < 0)
{
yVel *= -1;
}
if (yball.x < stage.stageWidth)
{
xVel *= -1;
}
if (yball.x < 0)
{
xVel *= -1;
}
if (yball.hitTestObject(ball_mc))
{
trace("boo");
xVel *= -1;
}
}
I cannot say I follow the logic of your conditionals. I think that is where your problem is. For the first set of code you have a y conditional defining the xVel parameter, which is likely wrong. Then I see where you change the xVel direction anytime the object's x is < the stage width.... I expect that have the object standing unable to make up its mind where to go. Rethink your conditionals and try to work out the bugs.
(forgot to mention that bit about the shared variables for the two obje
...Copy link to clipboard
Copied
yVel and xVel appear to be shared between both balls, therefore both will be affecting the same value. Over time when you continue to change their value in a similar way it will stack up, causing what you see.
Either make those variables unique names or make them a property of the balls and use that instead.
Copy link to clipboard
Copied
I cannot say I follow the logic of your conditionals. I think that is where your problem is. For the first set of code you have a y conditional defining the xVel parameter, which is likely wrong. Then I see where you change the xVel direction anytime the object's x is < the stage width.... I expect that have the object standing unable to make up its mind where to go. Rethink your conditionals and try to work out the bugs.
(forgot to mention that bit about the shared variables for the two objects)
Copy link to clipboard
Copied
Thank you, sinious and Ned.
You feedback help me get better understanding of the logic.
Copy link to clipboard
Copied
You're welcome and good luck!
Find more inspiration, events, and resources on the new Adobe Community
Explore Now