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().
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.