0 Replies Latest reply on Jan 6, 2011 10:22 AM by bradt8

# Balls on a line

I got a simple program that I've made. It works fine I have to ball object on stage that are attached to each other by a string or spring. The only thing is I want to make it so the ball can never be more than say 50 pixels away from each other. I think I've been staring at it for to long as I just can do the maths. I any one knows the maths or can point me in the right direction to get me started that would be great. It is the springTo function that controls the balls

var spring:Number = 0.1;

var friction:Number = 0.9;

var springLength:Number = 75;

ball1.vx = 0;

ball1.vy = 0;

ball2.vx = 0;

ball2.vy = 0;

var down:Boolean = false;

var placeX:Number;

var placeY:Number;

var placeXX:Number;

var placeYY:Number;

function onLoop(e:Event):void{

springTo(ball1, ball2);

springTo(ball2, ball1);

placeX = ball1.x;

placeY = ball1.y;

placeXX = ball2.x;

placeYY = ball2.y;

graphics.clear();

graphics.lineStyle(3, 0x000000, 100, false, LineScaleMode.NONE, CapsStyle.SQUARE);

graphics.moveTo(placeX, placeY);

graphics.lineTo(placeXX, placeYY);

}

function springTo(ballA, ballB){

//if(!down){

var dx:Number = ballA.x - ballB.x;

var dy:Number = ballA.y - ballB.y;

var angle:Number = Math.atan2(dy, dx);

var targetX:Number = ballB.x + Math.cos(angle) * springLength;

var targetY:Number = ballB.y + Math.sin(angle) * springLength;

ballA.vx += (targetX - ballA.x) * spring;

ballA.vy += (targetY - ballA.y) * spring;

ballA.vx *= friction;

ballA.vy *= friction;

ballA.x += ballA.vx;

ballA.y += ballA.vy;

//}

if(down){

ball1.x = mouseX;

ball1.y = mouseY;

}

}

function drag(e:MouseEvent):void{

down = true;

}