Reputation: 1215
I am making a unity 2d game wherein I want a car to be a draggable object along a curvy road. I have added the following script to the car which works for forward drag only. How can I detect whether user is draging in forward or backward direction inside mouseDrag event? I am new to unity and I prefer using only C# and not 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);
}
}
Upvotes: 1
Views: 7856
Reputation: 1770
I wrote this simple tutorial wich is basically 7 lines of code and works like a charm. Easy and simple. You just have to use the build in Unity event system instead to write long and useless code. No need to use an update or fixed update.
Upvotes: 1
Reputation: 1570
Please try this (Direction Algorithm is 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);
}
}
Upvotes: 0