KITASENJU DESIGN BLOG

memo, html, javascript, unity

ドラッグできるオブジェクト

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

public class DragObj : MonoBehaviour
{
    [SerializeField] private MeshRenderer _meshRenderer;
    private MaterialPropertyBlock _block;
    private bool _isDrag=false;
    private bool _isOver=false;
    private Vector3 _pastPos;

    // Start is called before the first frame update
    void Start()
    {
        _block=new MaterialPropertyBlock();

        var pos = MyPlayerPrefs.GetVector3(gameObject.name);
        //if(pos!=Vector3.zero){
            transform.position = pos;
        //}

    }

    // Update is called once per frame
    void Update(){
        if (Input.GetMouseButtonDown(0)){ // if left button pressed...
            if(_isOver){
                _isDrag=true;
            }
        }
        if (Input.GetMouseButtonUp(0)){ // if left button pressed...
            _isDrag=false;
            MyPlayerPrefs.Save();
        }

        if(_isDrag){
                var delta = 0.001f*(Input.mousePosition - _pastPos);
                transform.Translate(
                    delta.x,
                    delta.y,
                    0
                );
                MyPlayerPrefs.SetVector(gameObject.name,transform.position);
        }

            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit)){

                if(transform == hit.transform){
                    Debug.Log("HIT " + hit.transform.name);
                    _block.SetVector("_Color",Color.blue);
                    _isOver=true;
                }else{
                    _block.SetVector("_Color",Color.red);
                    _isOver=false;                    
                }
                // the object identified by hit.transform was clicked
                // do whatever you want
                
                                
            }else{
                _block.SetVector("_Color",Color.red);
                _isOver=false;
            }
            _meshRenderer.SetPropertyBlock(_block);
        //}

        _pastPos = Input.mousePosition;

    }
}

"FOOTER"