Unity3d-在RTS相机上拖放对象

时间:2018-07-02 19:33:10

标签: c# unity3d drag-and-drop

我有以下代码可将3d对象拖放到世界上:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpyAI : MonoBehaviour {
    Animator anim;

    private Vector3 screenPoint;
    private Vector3 offset;


    // Use this for initialization
    void Start () {
        anim = gameObject.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update () {

    }

    void OnMouseDown()
    {
        anim.SetBool("drag", true);
        screenPoint = Camera.main.WorldToScreenPoint(transform.position);
        offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }

    void OnMouseUp()
    {
        anim.SetBool("drag", false);
        anim.SetBool("idle", true);
    }
}

问题是: 在拖动对象时,有时会根据鼠标的移动而消失 拖动时如何使物体保持在地面上方?

1 个答案:

答案 0 :(得分:1)

最明显的变化是curScreenPoint的z值。使用the docs作为参考,它应该是:

Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane);

现在可能需要一些微调的行为,如果地面上有坡度或上面放着椅子或桌子等复杂碰撞物的物体,您可能想使物体升到地面上方。为此,您可能想从稍微高于curPosition计算的点向地面向下sphere cast。使用hitInfo查看下降的幅度,并相应地调整curPosition的y位置。