我正在制作一个统一的2d游戏,其中我想要一辆汽车在弯曲的道路上成为一个可拖动的物体。我已将以下脚本添加到仅适用于前向拖动的汽车中。 如何检测用户是否在mouseDrag事件中向前或向后拖动?我是团结的新手,我更喜欢只使用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);
}
}
答案 0 :(得分:0)
请尝试此操作(方向算法为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);
}
}
答案 1 :(得分:0)
我写了this简单的教程,基本上是7行代码,就像一个魅力。简单易用。你只需要在Unity事件系统中使用te build来编写冗长且无用的代码。 无需使用更新或固定更新。