点击目标物体 瞬移到那个物体的位置

这一次主要学到的内容: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;

            }


        }


    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值