单击鼠标移动精灵

时间:2017-10-17 13:11:14

标签: c# unity3d

您好我遵循了一个关于如何通过拖动移动精灵的utube教程,但我无法让它工作。

我是团结的新手,对不起,如果这有点简单

这是附在我的主相机上的脚本,我已将胶囊colllider附加到我的精灵

感谢您在高级方面提供的帮助

下一步是添加触摸输入

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

    public class DragMove : MonoBehaviour {

    public GameObject gameObjectToDrag; // refer to Go that being dragged

    public Vector3 Gocenter; // gameobject centre
    public Vector3 touchPosition; // touch or click position
    public Vector3 offSet; // vector between touchpoint/mouse click to the      object centre
    public Vector3 newGOCenter; // new center of object

    RaycastHit hit; // store hit object information

    public bool draggingmode = false; //   



// Use this for initialization
void Start () {

}

    // Update is called once per frame
    void Update() {

    //********************************
    // **Click to Drag****************
    //********************************

    // first frame when user click left button

    if (Input.GetMouseButtonDown(0))
    {
        // convert mouse position to ray
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        // if ray hit a collider (not 2dcollider)
        if (Physics.Raycast(ray, out hit))
        {
            gameObjectToDrag = hit.collider.gameObject;
            Gocenter = gameObjectToDrag.transform.position;
            touchPosition = Camera.main.ScreenToWorldPoint
(Input.mousePosition);
            offSet = touchPosition - Gocenter;
            draggingmode = true;
        }
    }

    // every frame when user hold left mouse
    if (Input.GetMouseButtonDown(0))
    {
        if (draggingmode)
        {
            touchPosition = Camera.main.ScreenToWorldPoint
(Input.mousePosition);
            newGOCenter = touchPosition - offSet;
            gameObjectToDrag.transform.position = new Vector3(newGOCenter.x, 
newGOCenter.y, newGOCenter.z);
        }
    }
    if (Input.GetMouseButtonUp(0))
    {
        draggingmode = false;
    }

    }
}

1 个答案:

答案 0 :(得分:0)

GetMouseButtonDown仅在第一帧返回true。 GetMouseButton用于检测按住鼠标按钮的时间。

// every frame when user hold left mouse
if (Input.GetMouseButtonDown(0))
{

应改为阅读

// every frame when user hold left mouse
if (Input.GetMouseButton(0))
{