实现鼠标拖动代码

当前位置 : 首页 > 网页制作 > CSS > 实现鼠标拖动代码

实现鼠标拖动代码

来源: 作者: 时间:2016-01-28 09:27
本脚本是根据momo研究院的一个脚本修改的,将此代码挂在照相机上,注意照相机必须是主相机,如何自己创建相机的话,要修改Tag,Tag必须是Main Cmarea,不然会报错,因为代码中设定的


脚本是根据momo研究院的一个脚本修改的,将此代码挂在照相机上,注意照相机必须是主相机,如何自己创建相机的话,要修改Tag,Tag必须是Main Cmarea,不然会报错,因为代码中设定的是main。主要功能是鼠标右键是旋转视角,有上下和左右,鼠标左键是拖动物体。唯一不足之处是鼠标左键只要按下就会拖动物体,再加个选中以后再拖动是比较好的。可以与鼠标拾取代码相结合一下就可以了。本代码以经过测试可以编译成功

using UnityEngine;

using System.Collections;


public class mousedrag: MonoBehaviour
{


public Transform target;//获得照相机焦点坐标

private float normalDistance = 3;



private float xSpeed = 250.0f;
private float ySpeed = 120.0f;


private int yMinLimit = -20;
private int yMaxLimit = 80;


private float x = 0.0f;
private float y = 0.0f;

private Vector3 screenPoint;
private Vector3 offset;

private Quaternion rotation = Quaternion.Euler(new Vector3(30f,0f,0f));
private Vector3 CameraTarget;
void Start ()
{

CameraTarget = target.position;

float z = target.transform.position.z - normalDistance;
transform.position =rotation * new Vector3(transform.position.x,transform.position.y,z);


transform.LookAt(target);

var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
}

void Update ()

{

//1代表鼠标右键按下,0代表鼠标左键按下

if(Input.GetMouseButton(1))
{
x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;

y = ClampAngle(y, yMinLimit, yMaxLimit);

var rotation = Quaternion.Euler(y, x, 0);
var position = rotation * new Vector3(0.0f, 0.0f, -normalDistance) + CameraTarget;

transform.rotation = rotation;
transform.position = position;

}else if(Input.GetMouseButtonDown(0))
{
screenPoint = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

if(Input.GetMouseButton(0))
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
target.transform.position = curPosition;
}
transform.LookAt(CameraTarget);

}

static float ClampAngle (float angle , float min ,float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
}
Tag:
网友评论

<