Вопрос №1
Возможно я не с того конца взялся(изучи программирование, почитай гайды, смотри видео, когда-нибудь сам дотикаешь до ответа на свой вопрос...), но в данный момент имеется загвоздка именно на самом начальном этапе:
Есть terrain, есть камера(параллельна террэйну, смотрит на него сверху вниз) - я хочу, чтобы перемещение камеры происходило посредством мыши(по типу RTS). Посему нашел в интернете следующий скрипт:
Синтаксис:
Используется csharp
using UnityEngine;
using System.Collections;
public class CameraMovement : MonoBehaviour {
//-------------------------------------------------------//
private Vector2 mouseButton2DownPoint, mouseButton2UpPoint; // точки, в которых мы нажали и отпустили правую кнопку мыши (по умолчанию отвечает за движение)
private Vector2 turnButtonDownPoint; // точка, в которой мы зажали клавишу поворота
private bool dragMouse, turnCamera; // перемещать и поворачивать ли мышь
//-------------------------------------------------------//
//-------------------------------------------------------//
public GameObject camera; // ГО используемой камеры
public float cameraMoveSpeedDamper = 0.02f; // коэффицент скорости перемещения мыши
public float maxCamHeight;
private float minCamHeight;
public float mouseWheelSpeed = 150.0f; // скорость масштабирования поля колесиком мышки
//-------------------------------------------------------//
void Start()
{
minCamHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position);
}
// Update is called once per frame
void Update()
{
minCamHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position);
if (Input.GetButtonDown("Move Camera"))
{
mouseButton2DownPoint = Input.mousePosition;
dragMouse = true;
}
if (Input.GetButtonUp("Move Camera"))
{
dragMouse = false;
mouseButton2UpPoint = Input.mousePosition;
}
if (Input.GetButtonDown("Turn Camera"))
{
turnCamera = true;
turnButtonDownPoint = Input.mousePosition;
}
if (Input.GetButtonUp("Turn Camera"))
{
turnCamera = false;
}
if (dragMouse) // перемещать ли камеру
{
Vector2 dragDifference = mouseButton2DownPoint - (Vector2)(Input.mousePosition); // на сколько юзер передвинул мышку
// устанавливаем вектору движения разницу между положениями мыши
Vector3 moveDirection = new Vector3(-dragDifference.x, 0, -dragDifference.y);
// Translating so move relative to where the camera currently is located
transform.Translate(moveDirection * cameraMoveSpeedDamper);
}
if (turnCamera) // поворачивать ли камеру
{
//transform.rotation *
Vector2 turnDifference = turnButtonDownPoint - (Vector2)(Input.mousePosition); // на сколько юзер повернул мышку
Vector3 turnDirection = new Vector3(-turnDifference.x, -turnDifference.x, -turnDifference.y);
//Quaternion zrot = Quaternion.AngleAxis(transform.rotation.eulerAngles.x + (-turnDifference.y * cameraMoveSpeedDamper * 10), Vector3.left);
transform.rotation = Quaternion.AngleAxis(transform.rotation.eulerAngles.y + (turnDirection.y * cameraMoveSpeedDamper), Vector3.up);
}
float mouseWheel = Input.GetAxis("Mouse ScrollWheel");
//if (mouseWheel != 0) // если пользователь крутил колесико мышки
{
float currentHeight = camera.transform.position.y;
// изменить высоту камер основываясь на заданной скорости
currentHeight -= mouseWheel * mouseWheelSpeed * Time.deltaTime;
// установить высоту камеры, не переходя мин/макс значений
if (currentHeight <= (minCamHeight + 3)) currentHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position) + 5;
if (!(currentHeight <= minCamHeight) && !(currentHeight >= maxCamHeight))
{
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
camera.transform.position = new Vector3(camera.transform.position.x, currentHeight, camera.transform.position.z);
}
}
}
}
using System.Collections;
public class CameraMovement : MonoBehaviour {
//-------------------------------------------------------//
private Vector2 mouseButton2DownPoint, mouseButton2UpPoint; // точки, в которых мы нажали и отпустили правую кнопку мыши (по умолчанию отвечает за движение)
private Vector2 turnButtonDownPoint; // точка, в которой мы зажали клавишу поворота
private bool dragMouse, turnCamera; // перемещать и поворачивать ли мышь
//-------------------------------------------------------//
//-------------------------------------------------------//
public GameObject camera; // ГО используемой камеры
public float cameraMoveSpeedDamper = 0.02f; // коэффицент скорости перемещения мыши
public float maxCamHeight;
private float minCamHeight;
public float mouseWheelSpeed = 150.0f; // скорость масштабирования поля колесиком мышки
//-------------------------------------------------------//
void Start()
{
minCamHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position);
}
// Update is called once per frame
void Update()
{
minCamHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position);
if (Input.GetButtonDown("Move Camera"))
{
mouseButton2DownPoint = Input.mousePosition;
dragMouse = true;
}
if (Input.GetButtonUp("Move Camera"))
{
dragMouse = false;
mouseButton2UpPoint = Input.mousePosition;
}
if (Input.GetButtonDown("Turn Camera"))
{
turnCamera = true;
turnButtonDownPoint = Input.mousePosition;
}
if (Input.GetButtonUp("Turn Camera"))
{
turnCamera = false;
}
if (dragMouse) // перемещать ли камеру
{
Vector2 dragDifference = mouseButton2DownPoint - (Vector2)(Input.mousePosition); // на сколько юзер передвинул мышку
// устанавливаем вектору движения разницу между положениями мыши
Vector3 moveDirection = new Vector3(-dragDifference.x, 0, -dragDifference.y);
// Translating so move relative to where the camera currently is located
transform.Translate(moveDirection * cameraMoveSpeedDamper);
}
if (turnCamera) // поворачивать ли камеру
{
//transform.rotation *
Vector2 turnDifference = turnButtonDownPoint - (Vector2)(Input.mousePosition); // на сколько юзер повернул мышку
Vector3 turnDirection = new Vector3(-turnDifference.x, -turnDifference.x, -turnDifference.y);
//Quaternion zrot = Quaternion.AngleAxis(transform.rotation.eulerAngles.x + (-turnDifference.y * cameraMoveSpeedDamper * 10), Vector3.left);
transform.rotation = Quaternion.AngleAxis(transform.rotation.eulerAngles.y + (turnDirection.y * cameraMoveSpeedDamper), Vector3.up);
}
float mouseWheel = Input.GetAxis("Mouse ScrollWheel");
//if (mouseWheel != 0) // если пользователь крутил колесико мышки
{
float currentHeight = camera.transform.position.y;
// изменить высоту камер основываясь на заданной скорости
currentHeight -= mouseWheel * mouseWheelSpeed * Time.deltaTime;
// установить высоту камеры, не переходя мин/макс значений
if (currentHeight <= (minCamHeight + 3)) currentHeight = Terrain.activeTerrain.SampleHeight(camera.transform.position) + 5;
if (!(currentHeight <= minCamHeight) && !(currentHeight >= maxCamHeight))
{
transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
camera.transform.position = new Vector3(camera.transform.position.x, currentHeight, camera.transform.position.z);
}
}
}
}
По комментариям в скрипте я примерно понял, что за что отвечает, но проблема в самом банальном наверное - как мне прикрутить этот скрипт к самой камере?) Я пробовал "Add Component" -> "New Script" -> "C#" -> Name = CameraMovement... Да я понимаю, что я нуб, но помогите кто как сможет - где я ошибся в своем алгоритме действий или дайте ссылочку на похожий по моему вопросу туториал...
Вопрос №2
Есть допустим исходник какого-либо приложения для Unity3d - как собственно его открыть с помощью Юнити?)) Там должен быть какой-то исполняющий файл? или что-то надо просто скопировать в корневую папку моего Юнити?
Такие вот детские вопросы, но если кто-то окажет помощь в разжевывании (а не отправит покорять просторы библиотек(в свободное время именно этим и занимаюсь)) буду очень признателен!