LoginSignup
10
11

More than 5 years have passed since last update.

[Unity]オブジェクトをドラッグで移動させる

Last updated at Posted at 2018-09-19

概要

オブジェクトをドラッグで動かす。
50hob-ka647.gif

対象

3DなゲームオブジェクトかつColliderがあるもの

コード

MovableBox.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovableBox : MonoBehaviour {

    private Vector3 moveTo;

    private bool beRay = false;

    // Use this for initialization
    void Start () {
        camera = Camera.main;
    }

    // Update is called once per frame
    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            RayCheck();
        }

        if (beRay) {
            MovePoisition();
        }

        if (Input.GetMouseButtonUp(0)) {
            beRay = false;
        }
    }

    private void RayCheck() {
        Ray ray = new Ray();
        RaycastHit hit = new RaycastHit();
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray.origin, ray.direction, out hit, Mathf.Infinity) && hit.collider == gameObject.GetComponent<Collider>()) {
            beRay = true;
        } else {
            beRay = false;
        }

    }

    private void MovePoisition() {

        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 10;

        moveTo = Camera.main.ScreenToWorldPoint(mousePos);
        transform.position = moveTo;

    }
}


解説

Ray

ある点からある点まで光線のようなものを飛ばして、それに何か当たったかを検知するもの。これが無いとドラックではなく瞬間移動してマウスの場所まで行く。

mousePos

Input.mousePositionでマウス自体の座標は取れるが、それではUnityの3D座標にはならないので、z座標を変え、ScreenToWorldPointで検出できる座標にしている。

moveToPos

現状では(マウスのx,マウスのy,0)に移動するので、z座標を書き換えるときはmoveToPos.z=値というように指定する必要がある。

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11