如何使用OnMouseDrag在屏幕上拖动对象? [英] How do I drag objects on the screen using `OnMouseDrag`?

查看:1145
本文介绍了如何使用OnMouseDrag在屏幕上拖动对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试做2D和3D.我希望播放器单击并拖动对象以将其堆叠.我尝试从视频复制和粘贴代码,但仍然无法正常工作.

Tried doing 2D and 3D. I want the player to click and drag objects to stack them. I tried copying and pasting code from a video and it still didn't work.

更新!现在它可以工作了,但它可以将物体传送到远离屏幕的位置.我希望播放器能够平滑地单击并拖动对象.

UPDATE! Now it kinda works but it teleports the object far off the screen. I want the player to be able to smoothly click and drag the object.

到目前为止的代码:

using UnityEngine;
using System.Collections;

public class DragObject : MonoBehaviour
{
    private float deltax, deltay;


    private void OnMouseDown()
    {
        deltax = 1f;//Camera.main.ScreenToWorldPoint(Input.mousePosition).x - transform.position.x;
        deltay = 1f; //Camera.main.ScreenToWorldPoint(Input.mousePosition).y - transform.position.y;
    }

    private void OnMouseDrag()
    {
        Vector2 currentTouchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector2((Input.mousePosition).x - deltax, (Input.mousePosition.y) - deltay);
    }
}

推荐答案

目前还不清楚您到底有什么确切的问题,显然您需要提供更多信息并更好地描述您的问题.但我会尽力提供帮助.

It's not clear at all what exact problem is for you, you obviously need to give more info and describe your issue better. But I'll try to help as I can.

要获取鼠标位置,您需要使用:

To get mouse position you need to use:

Input.mousePosition

如果您需要在二维坐标中定位鼠标,则可以使用以下方法:

If you need mouse position in 2d coordinates you can use this:

Vector2 currentTouchPos = mainCamera.ScreenToWorldPoint(Input.mousePosition);

这篇关于如何使用OnMouseDrag在屏幕上拖动对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆