卡牌拖拽效果—自制卡牌游戏之旅

2022-07-27,,,,

文章目录

  • 一、实现效果
  • 二、实现过程
    • 1. 想法
    • 2. 核心代码
    • 3. 完整代码

素材来源:影之诗国服大百科

内容简介:本篇主要介绍实现卡牌拖拽效果


一、实现效果

二、实现过程

1. 想法

当鼠标按住卡牌拖动的时候,鼠标点击的位置和卡牌的中心位置的距离应该是不变的。

① 如下直角坐标系:

B点为卡牌的中心点
A点为鼠标点击的点
A’点为鼠标拖动到下一个位置的点
要求此时卡牌中心点应该在哪

② 用A-B得到

A

B

=

B

A

A-B=\overrightarrow {BA}

AB=BA

并将向量平移到坐标轴原点得到P1

③ 用A’-P1得到

A

P

1

=

P

1

A

A'-P_{1}=\overrightarrow {P_{1}A'}

AP1=P1A

并平移到原点,最后得到B’

④ 因为|P1A’| 与 |OB’| 平行且相等,得A’B‘P1O为平行四边形,
所以|B’A’| = |OP1| = |BA|

2. 核心代码

因为处理Z轴的时候都是保证一致,所以只用处理X、Y轴就行

鼠标点击时候,pointerDisplacement获取到卡牌中心点到鼠标坐标的向量

    void OnMouseDown()
    {
        dragging = true;
        zDisplacement = -Camera.main.transform.position.z + transform.position.z;
        pointerDisplacement = -transform.position + MouseInWorldCoords();
    }

当鼠标移动的时候用鼠标坐标减去pointerDisplacement就可以得到移动后卡牌的中心点

    void Update ()
    {
        if (dragging)
        { 
            Vector3 mousePos = MouseInWorldCoords();
            //Debug.Log(mousePos);
            transform.position = new Vector3(mousePos.x - pointerDisplacement.x, mousePos.y - pointerDisplacement.y, transform.position.z);   
        }
    }

3. 完整代码

using UnityEngine;
using System.Collections;

public class DraggableTest : MonoBehaviour 
{
    // 当前是否拖动该卡牌的标志
    private bool dragging = false;
    // 从拖动对象的中心到鼠标点击的距离 
    private Vector3 pointerDisplacement = Vector3.zero;
    // 相机与鼠标Z轴上的距离
    private float zDisplacement;
    void OnMouseDown()
    {
        dragging = true;
        zDisplacement = -Camera.main.transform.position.z + transform.position.z;
        pointerDisplacement = -transform.position + MouseInWorldCoords();
    }
    void Update ()
    {
        if (dragging)
        { 
            Vector3 mousePos = MouseInWorldCoords();
            //Debug.Log(mousePos);
            transform.position = new Vector3(mousePos.x - pointerDisplacement.x, mousePos.y - pointerDisplacement.y, transform.position.z);   
        }
    }
    void OnMouseUp()
    {
        if (dragging)
        {
            dragging = false;
        }
    }   
    // 返回鼠标的世界坐标
    private Vector3 MouseInWorldCoords()
    {
        var screenMousePos = Input.mousePosition;
        //Debug.Log(screenMousePos);
        screenMousePos.z = zDisplacement;
        return Camera.main.ScreenToWorldPoint(screenMousePos);
    }

}

本文地址:https://blog.csdn.net/qq_43683939/article/details/110142904

《卡牌拖拽效果—自制卡牌游戏之旅.doc》

下载本文的Word格式文档,以方便收藏与打印。