-1

我需要通过在 C# Unity3D 中单击并拖动来移动立方体。我的代码目前通过点击一个按钮来创建立方体。

using UnityEngine;
using System.Collections;

public class CDraggable : MonoBehaviour 
{
    Texture btnimg;

    // Use this for initialization
    void Start ()
    {
    }

    // Update is called once per frame
    Update () 
    {
        //here to write mousedrag code.
    }

    void OnGUI() 
    {
        if (GUI.Button(new Rect(400, 250, 50, 50), btnimg))
        {
            //Debug.Log("Clicked the button with an image");
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(-0.7F, 2, 0);
        }
    } 

}
4

3 回答 3

3

将脚本添加DragRigidbody.js到您的相机。它包含在 unity 的默认资产中StandardAssets/Scripts/GeneralScripts/,它完全符合您的要求。

于 2013-07-04T06:55:21.463 回答
1

这可能会帮助你.. :)

Vector2 screenPoint = Vector2.Zero ;


void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(scanPos); 
    offset = scanPos - Camera.main.ScreenToWorldPoint(
        new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}

Vector3 curScreenPoint = Vector3.Zero;
Vector3 curPosition = Vector3.Zero;
void OnMouseDrag()
{
curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);

    curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    transform.position = curPosition;
}
于 2013-07-04T07:23:03.347 回答
0

我认为,如果您的游戏是 2D 的,这可能会有所帮助。

void Update{  
if (Input.GetMouseButton())
    {
        transform.position = Input.mousePosition;
    }
}
于 2017-11-09T19:22:10.187 回答