Skip to content

Instantly share code, notes, and snippets.

@edom18
Created June 5, 2018 03:01
Show Gist options
  • Save edom18/6bb52d6619495577b8e64624ababe15e to your computer and use it in GitHub Desktop.
Save edom18/6bb52d6619495577b8e64624ababe15e to your computer and use it in GitHub Desktop.
マウスでカメラ操作を行うスクリプト
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseCameraController : MonoBehaviour
{
[SerializeField]
private float _speed = 0.1f;
[SerializeField]
private float _rotSpeed = 0.1f;
private Vector2 _prevMovePos;
private Vector2 _prevRotPos;
private Vector2 ZERO_VEC2 = Vector2.zero;
private Transform _targetCamera;
#if UNITY_EDITOR
private void Start()
{
_targetCamera = GetComponent<Camera>().transform;
}
private void Update()
{
if (Input.GetMouseButton(0))
{
Move();
}
if (Input.GetMouseButton(1))
{
Rotate();
}
if (Input.GetMouseButtonUp(0))
{
_prevMovePos = ZERO_VEC2;
}
if (Input.GetMouseButtonUp(1))
{
_prevRotPos = ZERO_VEC2;
}
}
private void Rotate()
{
if (_prevRotPos == ZERO_VEC2)
{
_prevRotPos = Input.mousePosition;
return;
}
Vector2 current = Input.mousePosition;
Vector2 vec = (current - _prevRotPos) * _rotSpeed;
Vector3 euler = transform.rotation.eulerAngles;
euler.y += vec.x;
euler.x -= vec.y;
transform.rotation = Quaternion.Euler(euler);
_prevRotPos = current;
}
private void Move()
{
if (_prevMovePos == ZERO_VEC2)
{
_prevMovePos = Input.mousePosition;
return;
}
Vector2 current = Input.mousePosition;
Vector2 speedVec = (current - _prevMovePos) * _speed;
Vector3 moveVec = (transform.right * speedVec.x) + (transform.up * speedVec.y);
_targetCamera.position += moveVec;
_prevMovePos = current;
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment