physx exrcise 2-spring
/**
* Copyright J.J ( http://wonderfl.net/user/J.J )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/f8Ap
*/
// forked from flash.display's flash on 2013-7-9
package {
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.MovieClip;
import flash.geom.Point;
import flash.display.Sprite;
public class FlashTest extends Sprite {
private var fp:Point,dist:Point,extns:Point,damping:Point,restoring:Point,unit:Point
private var m:MovieClip
private var spring:Sprite
private const K_Damping:Number=-.2;
private const K_Spring:Number=-.2
private var draging:Boolean=false
private var wii:Number=50
public function FlashTest() {
stage.frameRate=60
dist=new Point;
extns=new Point;
damping=new Point;
restoring=new Point;
unit=new Point;
m=new MovieClip;
m.graphics.beginFill(0)
m.graphics.drawCircle(0,0,10);
m.graphics.endFill();
addChild(m)
m.x=stage.stageWidth/2
m.y=stage.stageHeight/2
fp=new Point(m.x,m.y)
m.x=m.y=m.vx=m.vy=0;
spring=new Sprite;
spring.x=fp.x
spring.y=fp.y
addChild(spring)
m.addEventListener(MouseEvent.MOUSE_DOWN,onMDown)
stage.addEventListener(MouseEvent.MOUSE_UP,onMUp)
this.addEventListener("enterFrame",loop);
// write as3 code here..
}
private function onMDown(e:MouseEvent):void{
draging=true
m.startDrag()
}
private function onMUp(e:MouseEvent):void{
draging=false
m.stopDrag()
}
private function DrawSpring(w:Number=200,amp:Number=5,freq:Number=1):void{
spring.graphics.clear()
spring.graphics.lineStyle(1)
spring.graphics.moveTo(0,0)
for(var i:int;i<w;i++){
var ang:Number=(Math.PI*2)*freq*i/w;
spring.graphics.lineTo(i,Math.sin(ang)*amp)
}
}
private function loop (e:Event):void{
dist.setTo(m.x-fp.x,m.y-fp.y);
var lng:Number=dist.length
if(lng>0) unit.setTo(dist.x/lng,dist.y/lng)
else unit.setTo(0,0)
extns.setTo(dist.x-(unit.x*wii),dist.y-(unit.y*wii))
restoring.setTo(extns.x*K_Spring,extns.y*K_Spring)
damping.setTo(m.vx*K_Damping,m.vy*K_Damping)
DrawSpring(lng,5,10);
var theta:Number=Math.atan2(dist.x,dist.y)*180/Math.PI
spring.rotation=-theta+90
//
if(draging==false){
m.vy+=3
m.vx+=restoring.x
m.vx+=damping.x
m.x+=m.vx
//
m.vy+=restoring.y
m.vy+=damping.y
m.y+=m.vy
}
}
}
}