[ActionScript 3.0] 表示オブジェクトの中心を原点に

Flashでは表示オブジェクトの左上隅がデフォルトの原点になっているが、これを表示オブジェクトの中心にしたほうがわかりやすい場合がある。

			var child:Shape = new Shape;
			child.graphics.beginFill(0);
			child.graphics.drawRect(0, 0, 20, 20);
			child.x = child.width / 2;
			child.y = child.height / 2;
			
			var parent:Sprite = new Sprite;
			parent.addChild(child);

表示オブジェクトを中央に揃える場合や、それらを等間隔に並べる場合は、このほうがコーディングしやすい。下記のような親のサイズに合わせて中心に置く形にすると、親のサイズが変わるたびに調整が必要になってしまう。

			var parent:Sprite = new Sprite;
			parent.graphics.beginFill(0x0000ff);
			parent.graphics.drawRect(0, 0, 40, 40);
			
			var child:Shape = new Shape;
			child.graphics.beginFill(0);
			child.graphics.drawRect(0, 0, 20, 20);
			child.x = (parent.width - child.width) / 2;
			child.y = (parent.height - child.height) / 2;
			
			parent.addChild(child);

カメラ機能(視点移動)を実装する際も、原点が中心のほうがわかりやすい。「原点は左上」という前提でコーディングしてきた人は、一度試してみてほしい。

ActionScript 3.0,Flash

Posted by takasho