入力と加速と表示
操作 ↑
←↓→ で移動
/**
* Copyright lilliliililiiliililiilil ( http://wonderfl.net/user/lilliliililiiliililiilil )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/99QI
*/
package {
import flash.events.Event
import flash.events.KeyboardEvent
import flash.display.Sprite
import flash.display.Shape
public class FlashTest extends Sprite {
public function FlashTest() {
stage.frameRate = 60
core = new Core()
view = new View()
this.addChild(view)
keyDowns = []
// 配列の初期化 * 中身を全部 0 で埋めてるだけです
for(var i:int=0;i<0x100;++i){ keyDowns[i] = 0 } // i++ ではなく ++i にした方が速いらしい
stage.addEventListener( Event.ENTER_FRAME ,onEnterFrame )
stage.addEventListener( KeyboardEvent.KEY_DOWN ,onKeyDown )
stage.addEventListener( KeyboardEvent.KEY_UP ,onKeyUp )
}
private var core:Core
private var view:Shape
private var keyDowns:Array
// キーボードの入力間隔は50ミリ秒くらいでかなり遅い
// キー入力と速度処理を同時にやると50ミリ秒で更新することになり、カクカクになってしまいます
// そこで入力を配列に保存しておき、速度処理は別に16ミリ秒に合わせてやることでスムーズに動かせるようになります
private function onKeyDown( event:KeyboardEvent ):void{ keyDowns[event.keyCode] = 1 }
private function onKeyUp ( event:KeyboardEvent ):void{ keyDowns[event.keyCode] = 0 }
private function onEnterFrame( event:Event ):void
{
var accelX :Number
var accelY :Number
var x :Number
var y :Number
var velocityX :Number
var velocityY :Number
var frictionRateX :Number
var frictionRateY :Number
// 値の展開
x = core.x
y = core.y
velocityX = core.velocityX
velocityY = core.velocityY
frictionRateX = core.frictionRateX
frictionRateY = core.frictionRateY
// 入力を加速度に変換
accelX = 2 * ( keyDowns[0x27] - keyDowns[0x25] ) // 0x25は「←」キーのキーコード 0x27は「→」キー
accelY = 2 * ( keyDowns[0x28] - keyDowns[0x26] ) // 0x26 ↑ 0x28 ↓
// 速度の適応
velocityX = ( accelX + velocityX ) * frictionRateX
velocityY = ( accelY + velocityY ) * frictionRateY
// 速度の限界を設定
if( velocityX < -32 ){ velocityX = -32 }else
if( velocityX > +32 ){ velocityX = +32 }
if( velocityY < -32 ){ velocityY = -32 }else
if( velocityY > +32 ){ velocityY = +32 }
// 座標の適応
x = x + velocityX
y = y + velocityY
// 座標の限界を設定
if( x < 0 ){ x = 0 }else
if( x > 433 ){ x = 433 }
if( y < 0 ){ y = 0 }else
if( y > 433 ){ y = 433 }
// 値の保存
core.x = x
core.y = y
core.velocityX = velocityX
core.velocityY = velocityY
core.frictionRateX = frictionRateX
core.frictionRateY = frictionRateY
// 表示へ適応
// 速度処理用のデータと、表示処理用のデータは別にしておくと
// 個々変更できるので修正がしやすいです
view.x = x
view.y = y
}
}
}
import flash.display.Shape;
class View extends Shape{
public function View(){
this.graphics.beginFill(0x000000)
this.graphics.drawRect(0,0,32,32)
this.graphics.endFill()
}
}
class Core{
public function Core(){}
public var x :Number = 0.0
public var y :Number = 0.0
public var velocityX :Number = 0.0
public var velocityY :Number = 0.0
public var frictionRateX :Number = 0.8
public var frictionRateY :Number = 0.8
}