获取方向鼠标拖动unity3d c#
本文关键字:unity3d 拖动 鼠标 方向 获取 | 更新日期: 2023-09-27 18:12:53
我正在制作一款unity 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);
}
}