0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unityエディター拡張】シーンビューの3Dカメラをマウス位置に合わせて拡大縮小する

Posted at

概要

Unityシーンビューの2Dモードでは標準に搭載されているマウス位置に合わせたカメラの拡大縮小機能を、3Dモードでも実装するエディター拡張です。イラストソフトなんかでは標準的なカメラの操作が非常にしやすい機能。これで捗る。
gif
標準機能っぽいのに調べても出てこなかったので自分で作りました。これだけのソースですがUnityの仕様に振り回されて大分苦労した…正確な計算は面倒だったのでしてません。拡大位置にズレはありますが、おおむね動作するかと思います。

TraceSceneViewCamera.cs

//Unity 2018.4.11f1
//	このスクリプトをプロジェクト下に置くだけで実行されます。
//	エディター拡張機能なので Editor フォルダに置くと良いです。

using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
static public class TraceSceneViewCamera
{
	static TraceSceneViewCamera()
	{
		//シーンビュー上のイベントを取得するためのメソッドを追加
		//			※この方法でないとメソッド内で全イベントが取得できない
		SceneView.onSceneGUIDelegate += onSceneGUIDelegate;
	}

	static private void onSceneGUIDelegate(SceneView scene)
	{
		//3Dモード時にマウススクロールにトレースする
		if (scene.in2DMode)
			return;
		if (Event.current.type != EventType.ScrollWheel)
			return;

		var camera = scene.camera.transform;

		//カーソルの画面中央からの差を計算
		var center = new Vector2(scene.position.width, scene.position.height) * 0.5f;
		var difference = Event.current.mousePosition - center;
		difference.x = difference.x / center.x * 0.1f;
		difference.y = -difference.y / center.y * 0.1f;

		//カメラの中心を拡大率に比例してカーソル方向に動かす
		var pivot = scene.pivot;
		pivot += camera.up * difference.y * -Event.current.delta.y * scene.size * 0.2f;
		pivot += camera.right * difference.x * -Event.current.delta.y * scene.size * 0.2f;

		scene.LookAtDirect(pivot, Quaternion.LookRotation(camera.forward));
	}
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?