使用Unity 3D中的触摸输入在地形上移动相机

Rod*_*ley 5 c# 3d touch unity-game-engine ios

我是Unity的新手,我正试图弄清楚如何使用触摸输入在地图/地形上移动相机.相机将俯视地形,旋转(90,0,0).地形位于第8层.我用键盘移动它没有任何问题,现在我正在尝试移动触摸,如果你想在iOS上保持预期的用途,它是非常不同的.

我可以在内置的iOS应用程序中想到的最好的例子是用户触摸屏幕的地图,只要手指停留在屏幕上,地图上的那个点就会留在手指下.因此,当用户移动他们的手指时,地图似乎随着手指移动.我无法找到显示如何以这种方式执行此操作的示例.我已经看过可能用鼠标移动相机或角色的例子,但它们似乎不能很好地转换为这种风格.

还发布在Unity3D上:

http://answers.unity3d.com/questions/283159/move-camera-over-terrain-using-touch-input.html

Jer*_*dak 14

以下应该是你需要的.请注意,使用"透视"相机时,在手指/光标与地形之间获得1对1的对应关系非常棘手.如果您将相机更改为拼写,下面的脚本应该为您提供手指/光标位置和地图移动之间的完美地图.有了"透视",你会注意到一点偏移.

你也可以用光线跟踪来做到这一点,但我发现这条路线很邋and而且不那么直观.

用于测试的相机设置(值从检查器中提取,因此将其应用于那里):

  1. 位置:0,20,0
  2. 方向:90,0,0
  3. 投影:透视/正交

using UnityEngine;
using System.Collections;

public class ViewDrag : MonoBehaviour {
Vector3 hit_position = Vector3.zero;
Vector3 current_position = Vector3.zero;
Vector3 camera_position = Vector3.zero;
float z = 0.0f;

// Use this for initialization
void Start () {

}

void Update(){
    if(Input.GetMouseButtonDown(0)){
        hit_position = Input.mousePosition;
        camera_position = transform.position;

    }
    if(Input.GetMouseButton(0)){
        current_position = Input.mousePosition;
        LeftMouseDrag();        
    }
}

void LeftMouseDrag(){
    // From the Unity3D docs: "The z position is in world units from the camera."  In my case I'm using the y-axis as height
    // with my camera facing back down the y-axis.  You can ignore this when the camera is orthograhic.
    current_position.z = hit_position.z = camera_position.y;

    // Get direction of movement.  (Note: Don't normalize, the magnitude of change is going to be Vector3.Distance(current_position-hit_position)
    // anyways.  
    Vector3 direction = Camera.main.ScreenToWorldPoint(current_position) - Camera.main.ScreenToWorldPoint(hit_position);

    // Invert direction to that terrain appears to move with the mouse.
    direction = direction * -1;

    Vector3 position = camera_position + direction;

    transform.position = position;
}
}
Run Code Online (Sandbox Code Playgroud)


Pav*_*ton 6

我想出了这个脚本(我把它附加到相机上):

private Vector2 worldStartPoint;

void Update () {

    // only work with one touch
    if (Input.touchCount == 1) {
        Touch currentTouch = Input.GetTouch(0);

        if (currentTouch.phase == TouchPhase.Began) {
            this.worldStartPoint = this.getWorldPoint(currentTouch.position);
        }

        if (currentTouch.phase == TouchPhase.Moved) {
            Vector2 worldDelta = this.getWorldPoint(currentTouch.position) - this.worldStartPoint;

            Camera.main.transform.Translate(
                -worldDelta.x,
                -worldDelta.y,
                0
            );
        }
    }
}

// convert screen point to world point
private Vector2 getWorldPoint (Vector2 screenPoint) {
    RaycastHit hit;
    Physics.Raycast(Camera.main.ScreenPointToRay(screenPoint), out hit);
    return hit.point;
}
Run Code Online (Sandbox Code Playgroud)