【发布时间】: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