/* 舞台上有个mc */ package { import flash.display.Sprite; import flash.events.Event; public class Bouncing extends Sprite { private var ball:Ball; private var vx:Number; private var vy:Number; //弹力系数有所损耗所以为-0.7不计损耗为-1 private var bounce:Number = -0.7; public function Bouncing() { init(); } private function init():void { ball = new Ball ; ball.x = stage.stageWidth / 2; ball.y = stage.stageHeight / 2; vx = Math.random() * 20 - 10; vy = Math.random() * 20 - 10; addChild(ball); addEventListener(Event.ENTER_FRAME,onEnter); } private function onEnter(e:Event):void { ball.x += vx; ball.y += vy; var left:Number = 50; var right:Number = stage.stageWidth - 50; var up:Number = 50; var down:Number = stage.stageHeight - 50; if (ball.x + ball.radius > right) { ball.x = right - ball.radius; vx *= bounce; } else if (ball.x - ball.radius < left) { ball.x = left + ball.radius; vx *= bounce; } if (ball.y + ball.radius > down) { ball.y = down - ball.radius; vy *= bounce; } else if (ball.y - ball.radius < up) { ball.y = up + ball.radius; vy *= bounce; } //判断ball碰到mc之后怎么办 if (ball.hitTestObject(mc)) { var dx:Number = ball.x - mc.x; var dy:Number = ball.y - mc.y; var dist:Number = Math.sqrt(dx * dx + dy * dy); var radians:Number = Math.atan2(dy,dx);//弧度 var drgress:Number=radians*180/Math.PI;//弧度转化成度 //(radians=drgress/(180/Math.PI)||radians=drgress/180*Math.PI) //trace(drgress); //vx = Math.cos(radians) * speed; //vy = Math.sin(radians) * speed; if(drgress<45&&drgress>-45) { ball.x=mc.x+mc.width/2+ball.width/2 vx *= bounce; } else if ((drgress>-180&&drgress<-135)||(drgress<180&&drgress>135)) { ball.x=mc.x-mc.width/2-ball.width/2 vx *= bounce; } if (drgress>-135&&drgress<-45) { ball.y=mc.y-mc.height/2-ball.height/2 vy *= bounce; } else if(drgress<135&&drgress>45) { ball.y=mc.y+mc.height/2+ball.height/2 vy *= bounce; } } } } }
package { import flash.display.Sprite; public class Ball extends Sprite { public var radius:Number; public var color:uint; public function Ball(radius:Number=10,color:uint=0Xff0000) { this.radius = radius; this.color = color; draw(); } public function draw():void { graphics.beginFill(color); graphics.drawCircle(0,0,radius); graphics.endFill(); } } }