【问题标题】:Get direction of mouse drag unity3d C#获取鼠标拖动的方向 unity3d C#
【发布时间】:2015-12-12 19:41:10
【问题描述】:

我正在制作一个统一的 2d 游戏,其中我希望汽车成为沿着弯曲道路的可拖动对象。我已将以下脚本添加到仅适用于向前拖动的汽车中。 如何检测用户在 mouseDrag 事件中是向前还是向后拖动?我是 Unity 新手,我更喜欢只使用 C# 而不是 js。

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider2D))]

public class TouchInput : MonoBehaviour {
private Vector3 screenPoint;
private Vector3 offset;
public float speed = 20.0f;
Rigidbody2D rb;

void Start(){
rb = gameObject.GetComponent<Rigidbody2D>();
}

void OnMouseDown(){

}

void OnMouseDrag(){
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
rb.velocity = new Vector3(150 * Time.deltaTime, 0, 0);
}

void OnMouseUp()
{
rb.velocity = new Vector3(0, 0, 0);
}
}

【问题讨论】:

  • 您可以使用 OnMouseDown() 在拖动后获取初始点,您可以使用 initialPoint 找到方向。你可以阅读this
  • 我想到了这个,但是如果用户向左拖动然后向右拖动而不抬起手指怎么办?
  • 你可以计算一下。在documentation 中:当鼠标按下时,每帧都会调用 OnMouseDrag。
  • 请用一段代码支持你的回答。

标签: c# unity3d mouseevent draggable


【解决方案1】:

我写了this 简单的教程,基本上只有 7 行代码,就像一个魅力。简单易行。您只需要使用 Unity 事件系统中的构建来编写冗长且无用的代码。 无需使用更新或固定更新。

【讨论】:

    【解决方案2】:

    请试试这个(方向算法是here):

    using UnityEngine;
    using System.Collections;
    
    [RequireComponent(typeof(BoxCollider2D))]
    public class TouchInput : MonoBehaviour
    {
        private Vector3 screenPoint;
        private Vector3 initialPosition;
        private Vector3 offset;
        public float speed = 20.0f;
    
        Rigidbody2D rb;
    
        void Start()
        {
            rb = gameObject.GetComponent<Rigidbody2D>();
        }
    
        void OnMouseDown()
        {
            Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 initialPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
        }
    
        void OnMouseDrag()
        {
            Vector3 cursorPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
            Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
            Vector3 heading = cursorPosition - initialPosition;
            Vector3 direction = heading / heading.magnitude; // heading magnitude = distance 
            rb.velocity = new Vector3(150 * Time.deltaTime, 0, 0);
            //Do what you want.
            //if you want to drag object on only swipe gesture comment below. Otherwise:
            initialPosition = cursorPosition;
        }
    
        void OnMouseUp()
        {
            rb.velocity = new Vector3(0, 0, 0);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多