这一次主要学到的内容:onmousedown系列函数只对脚本本身悬挂的物体有反应,如果要对其他物体有反应,可用GetMouseButtonDown;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class main : MonoBehaviour
{
private Vector3 point;
bool memory = false;
private Camera cam;
public GameObject go;
public static string btnName;
private Vector3 screenSpace;
private Vector3 offset;
public bool found;
private bool combine = false;
Vector3 currentScreenSpace;
Vector3 currentPosition;
public GameObject mainchar;
// Use this for initialization
void Start()
{
mainchar = this.gameObject;
cam = Camera.main;
}
// Update is called once per frame
void Update()
{
currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
// Debug.Log(ray.ToString());
//RaycastHit是一个结构体对象,用来储存射线返回的信息
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity))
{
{
found = true;
Debug.Log("object touched");
//Debug.DrawLine(ray.origin, hitInfo.point);
go = hitInfo.collider.gameObject;
Debug.Log(go.transform.position);
Debug.Log(mainchar.transform.position);
screenSpace = cam.WorldToScreenPoint(go.transform.position);
offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
btnName = go.name;
found = true;
if (Input.GetMouseButtonDown(0))
{
Debug.Log("mouse");
if (go.transform.tag == "element")
{
mainchar.transform.position = go.transform.position;
}
}
if (Input.GetMouseButtonUp(0))
{
found = false;
btnName = null;
}
}
}
}
}