簡體   English   中英

獲取鼠標拖動方向 unity3d C#

[英]Get direction of mouse drag unity3d C#

我正在制作一個統一的 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);
}
}

我寫了 這個簡單的教程,它基本上只有 7 行代碼,而且效果很好。 簡單易行。 您只需要使用 Unity 事件系統中的構建來編寫冗長無用的代碼。 無需使用更新或固定更新。

請試試這個(方向算法在這里):

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM