как перетащить спрайт в мир-холст мышкой? - PullRequest
0 голосов
/ 24 апреля 2019

У меня есть морозильник, в нем есть немного еды, Это бар на холсте, который я сменил на тип мира - Холст. но когда я использую код ниже, спрайт не привязан к mousePos

transform.localPosition = Input.mousePostion;

1 Ответ

0 голосов
/ 24 апреля 2019

Прикрепите этот код к вашему объекту:
1 - рассчитать смещение расстояния между вашим объектом и камерой (в мировом пространстве)
2- выберите объект, который вы хотите переместить, используя приведение лучей.
3 - в функции обновления выбранный объект должен следовать обновленным координатам (смещение + положение объекта в мире)

using UnityEngine;
using System.Collections;

public class DragAndDrop : MonoBehaviour
{  
    private bool _mouseState;
    private GameObject target;
    public Vector3 screenSpace;
    public Vector3 offset;


    // Update is called once per frame
    void Update ()
    {
        // Debug.Log(_mouseState);
        if (Input.GetMouseButtonDown (0)) {

            RaycastHit hitInfo;
            target = GetClickedObject (out hitInfo);
            if (target != null) {
                _mouseState = true;
                screenSpace = Camera.main.WorldToScreenPoint (target.transform.position);
                offset = target.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0));
            }
        }
        if (Input.GetMouseButtonUp (0)) {
            _mouseState = false;
        }
        if (_mouseState) {
            //keep track of the mouse position
            var curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0);

            //convert the screen mouse position to world point and adjust with offset
            var curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;

            //update the position of the object in the world
            target.transform.position = curPosition;
        }
    }


    GameObject GetClickedObject (out RaycastHit hit)
    {
        GameObject target = null;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray.origin, ray.direction * 10, out hit)) {
            target = hit.collider.gameObject;
        }

        return target;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...