Unity 之鼠标滑动屏幕或拖动物体
程序员文章站
2022-07-14 09:39:26
...
直接把代码挂载到相机上面,参数都调好了,想改的自己改,也可以改成拖动物体,直接挂载到需要拖动的物体上面即可,如果拖动位置不对,就把世界坐标系转为屏幕坐标系,我这里用的世界坐标系,最后一行为注释掉的世界坐标系转为屏幕坐标系的方法
using UnityEngine;
using System.Collections;
public class Controll : MonoBehaviour
{
private bool isMouseDown = false;
private Vector3 lastMousePosition = Vector3.zero;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
isMouseDown = true;
}
if (Input.GetMouseButtonUp(0))
{
isMouseDown = false;
lastMousePosition = Vector3.zero;
}
if (isMouseDown)
{
// print("lastMousePosition: " + lastMousePosition);
// print("Input.mousePosition: " + Input.mousePosition);
if (lastMousePosition != Vector3.zero)
{
Vector3 offset = Input.mousePosition - lastMousePosition;
// print("offset: " + offset);
transform.position = transform.position -offset*0.05f;
// print("相机位置: "+transform.position);
}
lastMousePosition = Input.mousePosition;
//lastMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); //世界坐标系转换为屏幕坐标系
}
}
}
推荐阅读