- Home /
Why does "draggable" MonoBehavior cause the object to be moved in the opposite direction?
I'm new to c#. I created this behavior that can be attached to a GameObject allowing the object to be moved according to Touch input position. I've followed many examples all which use this.transform.Translate() to translate the touch position to the object position. However, the object moves the opposite of the touch input. I've been reading (on answers and docs) and can't seem to figure out why.
using UnityEngine;
using System.Collections;
public class DraggableBehavior : MonoBehaviour {
public bool isSelected = false;
public float speed = 0.1F;
void Start () {
}
void Update () {
if (Input.touchCount > 0) {
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began) {
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit ;
if (Physics.Raycast (ray, out hit)) {
bool imSelected = (hit.transform.gameObject == this.gameObject);
if (this.isSelected == false && imSelected) {
this.isSelected = true;
Debug.Log(this.gameObject.name + " was selected");
} else {
this.isSelected = false;
}
}
}
if (touch.phase == TouchPhase.Moved && this.isSelected) {
Vector2 touchDeltaPosition = touch.deltaPosition;
transform.Translate(-touchDeltaPosition.x * speed, -touchDeltaPosition.y * speed, 0);
}
}
}
}
I'm using the iSelected property for another use. See the second if block in Update().
Apples, thanks. That was one of the first things I tried but I think the result was that the object then didn't move. I will try again. Unity Remote is really acting up on me so this is taking forever.
Apples, you were right. The movement is quite exaggerated in reference to the touch movement but at least it's right. Not sure why the examples in the docs have the values negative.
I can't vote your comment best answer because it won't let me convert it.
Answer by Apples_mmmmmmmm · Aug 17, 2012 at 09:42 PM
for the line
transform.Translate(-touchDeltaPosition.x speed, -touchDeltaPosition.y speed, 0);
the negatives are most likely causing the opposite movement.
try
transform.Translate(touchDeltaPosition.x speed, touchDeltaPosition.y speed, 0);
instead.
Please use 'answer' when you're answering. If asking for more info, that would be a comment.
Your answer
Follow this Question
Related Questions
How to instantiate object at touch position? 3 Answers
How to make object follow touch position?Pls Help 0 Answers
Drag Object, same speed as mouse/touch 3 Answers
How do I re-enable input after dragging off iPad screen? 0 Answers
How do you Draw a Line Using your Finger's Position on Android 3 Answers