0
\$\begingroup\$

I'm making a VR game in Unity.

I want to select a cylinder with ray interactor and drag it, and as I drag, it should stretch.

This is the code I have currently for 2D:

[RequireComponent(typeof(Collider))]

public class ScaleWithDrag : MonoBehaviour
{
    public Transform WorldAnchor;
    private Camera mainCamera; //stores the reference of the camera
    private float CameraZDistance; //move the object
    private Vector3 InitialScale; //hold the inital scale of the gameobject

    void Start()
    {
        InitialScale = transform.localScale;
        mainCamera = Camera.main;
        CameraZDistance = mainCamera.WorldToScreenPoint(transform.position).z;
    }
    private void OnMouseDrag()
    {
        Vector3 MouseScreenPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, CameraZDistance); //z axis added to screen point
        Vector3 MouseWorldPosition = mainCamera.ScreenToWorldPoint(MouseScreenPosition); //screen point conversted into world point

        // change transform
        float Distance = Vector3.Distance(WorldAnchor.position, MouseWorldPosition);//change scale
        transform.localScale = new Vector3(InitialScale.x, Distance/2f, InitialScale.z);// /2 for cylinder

        Vector3 middlePoint = (WorldAnchor.position + MouseWorldPosition) / 2f;
        transform.position = middlePoint;

        //adjjust the rotation of the game object
        Vector3 rotationDirection = (MouseWorldPosition - WorldAnchor.position); //change rotation
        transform.up = rotationDirection;
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ How do you want the cylinder to stretch? Providing a diagram often helps when trying to explain spatial/geometric questions. \$\endgroup\$
    – DMGregory
    Sep 20 at 0:23
  • \$\begingroup\$ like for example when you select the cylinder with the trigger and till to release the trigger it should stretch along with the raycast! if that makes sense! \$\endgroup\$
    – SPP
    Sep 21 at 1:11
  • \$\begingroup\$ No, it does not, that's why I requested a diagramm.There are at least three ways it could stretch in response to dragging actions. Show us which one you want. \$\endgroup\$
    – DMGregory
    Sep 21 at 1:16
  • \$\begingroup\$ Ohk! I'm new to Unity so first can you tell those three ways you could stretch! \$\endgroup\$
    – SPP
    Sep 21 at 14:05

0

You must log in to answer this question.

Browse other questions tagged .