【練習】ボールと板の跳ね返り(不十分)
/**
* Copyright Tamanegi_kenshi ( http://wonderfl.net/user/Tamanegi_kenshi )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/ikuX
*/
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Rectangle;
public class FlashTest extends Sprite {
private var ball:Ball;
private var rect:Rect;
private var ballRadius:int =20;//ballの半径
private var friction:Number=1.1;
private var gravity:Number=0;
private var bounce:Number=-1;
public function FlashTest() {
init();
}
private function init():void{
//ボールの作成
ball = new Ball(0x00ff00,ballRadius);
addChild(ball);
ball.x=ball.y=100;
ball.vx=(Math.random()*10)+5;
ball.vy=Math.random()*10;
//長方形の作成
rect = new Rect(200);
addChild(rect);
rect.y=400;
rect.rotation=0;
addEventListener(Event.ENTER_FRAME,onEnter);
}
//EnterFrameの設定***********************************************************
private function onEnter(event:Event):void{
rect.x =mouseX;
ball.vy+=gravity;
ball.x+=ball.vx;
ball.y+=ball.vy;
//ballとrectとの跳ね返り
var bound:Rectangle=rect.getBounds(this);
if(ball.x>bound.left && ball.x<bound.right){
var angle:Number=rect.rotation*Math.PI/180;
var cos:Number=Math.cos(angle);
var sin:Number=Math.sin(angle);
var x1:Number=ball.x-rect.x;
var y1:Number=ball.y-rect.y;
var y2:Number=cos*y1-sin*x1;
var vy1:Number=cos*ball.vy-sin*ball.vx;
if(y2>-ball.height/2 && y2<vy1){
var x2:Number=cos*x1+sin*y1;
var vx1:Number=cos*ball.vx+sin*ball.vy;
y2=-ball.height/2;
vy1*=bounce;
x1=cos*x2-sin*y2;
y1=cos*y2+sin*x2;
ball.vx=cos*vx1-sin*vy1;
ball.vy=cos*vy1+sin*vx1;
ball.x=rect.x+x1;
ball.y=rect.y+y1;
}
}
//壁との跳ね返りの設定
if(ball.x+ballRadius>stage.stageWidth){
ball.x=stage.stageWidth-ballRadius;
ball.vx *=-1;
}else if(ball.x<ballRadius){
ball.x=0+ballRadius;
ball.vx *=-1;
}else if(ball.y+ballRadius>stage.stageHeight){
ball.vy*=-1;
}else if(ball.y<0+ballRadius){
ball.y=0+ballRadius;
ball.vy *=-1;
}
}
}
}
//*********************************************************************************
//*********************************************************************************
//Ballクラスの作成
import flash.display.Sprite;
import flash.display.GradientType;
import flash.geom.Matrix;
import flash.accessibility.Accessibility;
class Ball extends Sprite{
public var vx:Number=0;
public var vy:Number=0;
public function Ball(color:uint=0x000000,size:int=10){
graphics.beginFill(color);
graphics.drawCircle(0,0,size);
graphics.endFill();
}
}
//Rectクラスの作成
import flash.display.Sprite;
class Rect extends Sprite{
public function Rect(size:uint){
graphics.beginFill(0x000000);
graphics.drawRect(-size/2,-5/2,size,10);
}
}