Search Unity

How to have a child Camera object move a parent object (with code)

Discussion in 'Scripting' started by BokuDev, Mar 3, 2016.

  1. BokuDev

    BokuDev

    Joined:
    Jan 2, 2014
    Posts:
    81
    HI I'm working on a VR game with hookshot script, and the script works great without a VR headset and works by attaching it to the steam VR camera, but I learned quickly that once you are in VR mode the camera becomes a child of the roomscale object.

    How do I make it so the script is still attached to the steam vr camera and its gaze is still the method of aiming, BUT it moves the parent object "roomscale bounds" instead?

    Perhaps some way to place the parent object in the inspector.


    using UnityEngine;
    using System.Collections;

    public class HookShot : MonoBehaviour
    {
    public float PullSpeed = 10f;
    public float MaxDistance = 10f;
    public string Tag = string.Empty;

    private bool isFrozen;

    protected void Update ()
    {
    if (isFrozen)
    {
    return;
    }

    RaycastHit hit;

    if (Physics.Raycast (transform.position, transform.forward, out hit, MaxDistance))
    {
    if (string.IsNullOrEmpty (Tag) || hit.collider.CompareTag (Tag))
    {
    // hit valid target
    // you can display graphics here
    // showing that a hook is possible

    var deviceIndex = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.First);
    if (deviceIndex != -1 && SteamVR_Controller.Input(deviceIndex).GetPressDown(SteamVR_Controller.ButtonMask.Trigger))
    {
    StartCoroutine (Hook (hit.point));
    }
    }
    }
    }

    private IEnumerator Hook (Vector3 position)
    {
    isFrozen = true;

    while ((transform.position - position).sqrMagnitude > 0.5f)
    {
    transform.position = Vector3.MoveTowards (transform.position, position, Time.deltaTime * PullSpeed);
    yield return null;
    }

    isFrozen = false;
    }
    }
     
    Last edited: Mar 3, 2016
  2. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    With the script attached to the camera, the Hook coroutine moves the camera to the target hit point. If you want to move the hit target to the camera you don't use transform.position = ... You would have to use, target.transform.position = .....

    If that transform is the parent of the camera, of course, this would move the camera as well. to circumvent this you capture the world position of the camera, do the move, then re-assign the camera back to that position before you yield.
     
  3. BokuDev

    BokuDev

    Joined:
    Jan 2, 2014
    Posts:
    81

    I'm not trying to move the hit point to the camera,

    I'm trying to have the script STAY on the camera object, but instead of changing the cameras position it moves an object in the inspector to that target hit point.