【问题标题】:Unity3d - Drag and Drop object on RTS cameraUnity3d - 在 RTS 相机上拖放对象
【发布时间】:2018-07-02 19:33:10
【问题描述】:

我有这段代码可以在世界上拖放 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);
    }
}

问题是: 当我拖动对象时,有时,取决于鼠标的移动,它会经历 如何让对象在拖动时保持在地面之上?

【问题讨论】:

    标签: c# unity3d drag-and-drop


    【解决方案1】:

    最明显应该改变的是 curScreenPoint 的 z 值。以the docs为参考,大概应该是:

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

    现在,为了更精细地调整行为,如果地面有斜坡或带有复杂碰撞器的物体(如椅子或桌子),您可能希望使对象升起至地面以上。为此,您可能希望从略高于curPosition 中计算的点向下朝向地面执行sphere cast。使用 hitInfo 查看它下降了多少,并相应地调整 curPosition 的 y 位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多