OT2O
OT2O

Reputation: 139

Move Object Using Raycast

I am trying to move the y position of a UI element in it's local space by clicking and dragging with the SteamVR controller and a raycast. I am getting what appear to me to be unpredictable results.

I am trying to get the position of the raycast at the start of the drag and move it the distance between where it is and where it was started while dragging.

Here is my code:

if (hit.transform.name == "Content" && scrollSet == false)
{
    content = hit.transform;
    scrollSet = true;
    scrollPos = hit.transform.position ;
}

if (scrollSet == true)
{
    if (rController.triggerPressed)
    {
        y = hit.transform.position.y - scrollPos.y;
        content.transform.localPosition = new Vector3(content.transform.localPosition.x,  content.localPosition.y + y, content.transform.localPosition.z);
    }
    else
    {
        scrollSet = false;
    }
}

Upvotes: 0

Views: 2568

Answers (1)

Raghu Ariga
Raghu Ariga

Reputation: 1129

you can convert the .MovePosition to .MoveTowards. But it still jumped around. It turns out that the code was only executing during the frame in which you right-clicked, so move it out of the if statement.

Here's the entire script placed into the main camera. You always need to have a target selected, so to prevent errors you need to put a gameObject with a rigidbody into "bTarg".

public class ClickTarget : MonoBehaviour {

private GameObject target; private Vector3 destination; private float distance; private Vector3 tTrans;

public GUIText targetDisplay; public float speed; public GameObject bTarg;

void Start () { targetDisplay.text = ""; distance = 0.0f; target = bTarg; }

void Update () { if(Input.GetButtonDown("Fire1")){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray, out hit)){ if(hit.collider != null){ if(hit.collider.tag == "Unit"){ target = hit.collider.gameObject; targetDisplay.text = "Unit: " + hit.collider.gameObject.name; destination = target.transform.position; target.rigidbody.freezeRotation = false; } if(hit.collider.tag == "Building"){ target = hit.collider.gameObject; targetDisplay.text = "Building: " + hit.collider.gameObject.name; } } } } }

void FixedUpdate(){ if (Input.GetButtonDown ("Fire2") && target.tag == "Unit" && GUIUtility.hotControl == 0) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray,out hit)){ destination = hit.point; } }

 tTrans = target.transform.position;
 distance = Vector3.Distance (tTrans, destination);
 if(target.tag == "Unit"){
     if (distance > .2f) {
         target.transform.LookAt (destination);
         target.transform.position = Vector3.MoveTowards (target.transform.position, destination, speed);
         target.rigidbody.freezeRotation = true;
     }
 }
} }

Upvotes: 0

Related Questions