Reputation: 57
Using the Touch inputs I know how to drag a gameobject. But what I need to do is to (upon release of drag) check the speed of the drag and have the object move a bit further. So if I drag the object fast and release it it will move a bit in the dragged direction after releasing it. As it is now it simply stops at the position where I remove my finger. Anyone know how this is done?
What I have now is:
private Vector3 dist, distEnd;
float posX;
float posY;
void OnMouseDown() {
dist = Camera.main.WorldToScreenPoint (transform.position);
posX = Input.mousePosition.x - dist.x;
posY = Input.mousePosition.y - dist.y;
}
void OnMouseDrag()
{
Vector3 curPos = new Vector3 (Input.mousePosition.x - posX, Input.mousePosition.y - posY, dist.z);
Vector3 worldPos = Camera.main.ScreenToWorldPoint (curPos);
transform.position = worldPos;
}
void OnMouseUp() {
distEnd = Camera.main.WorldToScreenPoint (transform.position);
}
Then I added a RigidBody2d to the object - trying to add force to it - but I suppose I need to calculate the speed and direction of drag/mouse - before I can add directional force to the object??
GetComponent<Rigidbody2D> ().AddForce (Vector2 (FORCE_DIRECTION_X, FORCE_DIRECTION_Y));
But I'm having difficulties calculating direction and speed of drag.
Any help is appreciated!
Thanks.
Upvotes: 0
Views: 897
Reputation: 57
Right, I finally found an answer :-) I have included a script for others to use (I did not come up with the solution though).
Maybe someone could use it as well - alter variable "SmoothTime" so set time before drag-speed is 0.
using UnityEngine;
using System.Collections;
public class dragMap : MonoBehaviour {
private Vector3 _screenPoint;
private Vector3 _offset;
private Vector3 _curScreenPoint;
private Vector3 _curPosition;
private Vector3 _velocity;
private bool _underInertia;
private float _time = 0.0f;
public float SmoothTime = 2;
void Update()
{
if(_underInertia && _time <= SmoothTime)
{
transform.position += _velocity;
_velocity = Vector3.Lerp(_velocity, Vector3.zero, _time);
_time += Time.smoothDeltaTime;
}
else
{
_underInertia = false;
_time = 0.0f;
}
}
void OnMouseDown()
{
_screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
_offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPoint.z));
//Screen.showCursor = false;
_underInertia = false;
}
void OnMouseDrag()
{
Vector3 _prevPosition = _curPosition;
_curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPoint.z);
_curPosition = Camera.main.ScreenToWorldPoint(_curScreenPoint) + _offset;
_velocity = _curPosition - _prevPosition;
transform.position = _curPosition;
}
void OnMouseUp()
{
_underInertia = true;
//Screen.showCursor = true;
}
}
Upvotes: 0